Calendar Date Object in Java

Source: Internet
Author: User
Tags dateformat time and date


Reprint Online Profile
Calendar C = calendar.getinstance ();//Create an instance by default is the current moment

C.get (calendar.year);

C.get (Calendar.month);

C.get (calendar.date);//Get year, month, day of course, you can also note that the month here is more special starting from 0

C.get (Calendar.day_of_week);//Gets the current date in the day of the week from 1-7 to six

C.getactualmaximum (calendar.day_of_month);//Gets the maximum number of days in the month that is the date of the month
C.get (calendar.day_of_month);//The Day of the month in which the current number of days

C.set (2011, 10, 13);//Specify a date

int nowday = C.get (calendar.day_of_month);

C.set (Calendar.date, nowday+3);//3 days after the date

C.add (calendar.date, x);//go to the period of the specified number of days, take the date of the past day with negative numbers, take the future days with positive numbers, in the "X" where the world such as C.add (Calendar.date,-1) go to the date before the current date
C.gettime ()

Reprint
Common functions in Java for time-date operations
1. Calculate the maximum number of days for a January
Calendar time=calendar.getinstance ();
Time.clear ();
Time.set (calendar.year,year);
Time.set (calendar.month,i-1);///Note that Calendar object default January is 0
int Day=time.getactualmaximum (calendar.day_of_month);//number of days of the month
Note: Before using the Set method, you must clear it, otherwise many of the information will inherit from the current time of the system
Conversion of 2.Calendar and date
(1) Calendar converted to date
Calendar cal=calendar.getinstance ();
Date Date=cal.gettime ();
(2) Date converted to Calendar
Date Date=new date ();
Calendar cal=calendar.getinstance ();
Cal.settime (date);
3. Format output Date Time
Date Date=new date ();
SimpleDateFormat df=new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss");
System.out.println (Df.format (date));
4. Calculate the week ordinal of a year
(1) Calculate a day is the first week of the year
Calendar cal=calendar.getinstance ();
Cal.set (Calendar.year, 2006);
Cal.set (Calendar.month,;
Cal.set (Calendar.day_of_month, 3);
int Weekno=cal.get (calendar.week_of_year);
(2) Calculate the number of weeks of the year
SimpleDateFormat df=new SimpleDateFormat ("Yyyy-mm-dd");
Calendar cal=calendar.getinstance ();
Cal.set (Calendar.year, 2006);
Cal.set (calendar.week_of_year, 1);
Cal.set (Calendar.day_of_week, calendar.monday);
System.out.println (Df.format (Cal.gettime ()));
Output:
2006-01-02
Usage of 5.add () and Roll ()
(1) Add () method
SimpleDateFormat df=new SimpleDateFormat ("Yyyy-mm-dd");
Calendar cal=calendar.getinstance ();
Cal.set (Calendar.year, 2006);
Cal.set (Calendar.month,;
Cal.set (Calendar.day_of_month, 3);
Cal.add (Calendar.date,-4);
Date Date=cal.gettime ();
System.out.println (Df.format (date));
Cal.add (Calendar.date, 4);
Date=cal.gettime ();
System.out.println (Df.format (date));
Output:
2006-08-30
2006-09-03
(2) Roll method
Cal.set (Calendar.year, 2006);
Cal.set (Calendar.month,;
Cal.set (Calendar.day_of_month, 3);
Cal.roll (Calendar.date,-4);
Date=cal.gettime ();
System.out.println (Df.format (date));
Cal.roll (Calendar.date, 4);
Date=cal.gettime ();
System.out.println (Df.format (date));
Output:
2006-09-29
2006-09-03
It can be seen that the roll () method loops within this month and generally uses the Add () method;
6. Calculate the number of days between two times in the middle of an arbitrary time
(1) Pass into calendar object

/** *//** calculates the number of days between two time intervals
* @param startday start time
* @param endday End time
* @return
*/
public int getintervaldays (Calendar startday,calendar endday) ... {
Make sure StartDay is before Endday
if (Startday.after (endday)) ... {
Calendar Cal=startday;
Startday=endday;
endday=cal;
}
The number of milliseconds to get two time respectively
Long Sl=startday.gettimeinmillis ();
Long El=endday.gettimeinmillis ();

Long EI=EL-SL;
Calculates the number of days between intervals based on milliseconds
return (int) (ei/(1000*60*60*24));
}

(2) passing in a Date object
/** *//** calculates the number of days between two time intervals
* @param startday start time
* @param endday End time
* @return
*/
public int getintervaldays (Date startday,date endday) ... {
Make sure StartDay is before Endday
if (Startday.after (endday)) ... {
Date Cal=startday;
Startday=endday;
endday=cal;
}
The number of milliseconds to get two time respectively
Long Sl=startday.gettime ();
Long El=endday.gettime ();

Long EI=EL-SL;
Calculates the number of days between intervals based on milliseconds
return (int) (ei/(1000*60*60*24));
Similarly, you can use the same method to calculate the number of hours, minutes, seconds, and so on for any two-time interval.
Note: The above method is completely time-based, and sometimes not satisfactory, such as:
startday= "2006-10-11 20:00:00"
endday= "2006-10-12 8:00:00"
The result is 0, but we may be able to make the calculation result 1, which can be implemented as follows:
Before you pass the parameter, set the Endday time, such as:
Endday.set (Calendar.hour_of_day, 23);
Endday.set (Calendar.minute, 59);
Endday.set (Calendar.second, 59);
Endday.set (Calendar.millisecond, 59);
Then it goes in Startday,endday, and the result is as we wish. However, if the above method is troublesome, you can refer to the following methods:
(3) Improve the method of accurately calculating the number of days apart
public int Getdaysbetween (Calendar d1, calendar D2) ... {
if (D1.after (D2)) ... {//swap dates so D1 are start and D2 is end
Java.util.Calendar swap = D1;
D1 = D2;
D2 = swap;
}
int days = D2.get (calendar.day_of_year)-D1.get (calendar.day_of_year);
int y2 = d2.get (calendar.year);
if (D1.get (calendar.year)! = y2) ... {
D1 = (Calendar) d1.clone ();
Do ... {
Days + = D1.getactualmaximum (calendar.day_of_year);//Get the actual day of the year
D1.add (calendar.year, 1);
} while (D1.get (calendar.year)! = y2);
}
return days;
}
2007-04-24 14:34 Author: java-he
Re:java a word of skill (constantly added)
Date formatting classifications in Java: Java base time formatting
I. Acquisition, setting, and formatting of dates in Java
1) Java provides 3 date classes: Date, calendar, and DateFormat.
The date () method is primarily used to create date objects and obtain dates;
The Calendar () method is mainly used to get and set the date;
The DateFormat () method is primarily used to create date formatters, which are then converted by the formatter to various date format string outputs.
2) The base date specified in the Java language is Greenwich Mean Time 1970.1.1.00:00:00, and the current date is converted from the number of milliseconds that have elapsed since the base date.
3) The Datefomat class is in the Java.text package, and the date and calendar classes are in the Java.util package.
4) Examples are as follows:
Import java.util.*;
Import java.text.*;

public class Displaydate {
public static void Main (string[] args) {
Date today;
Calendar now;
DateFormat F1,f2;
String s1,s2;

System.out.println ("\ n Displays the relevant usage of the date class");

Today = new Date ();
System.out.println ("new Date () = \ T" + today);

System.out.println ("\ n use DateFormat class to display various date formats");

Show various date formats
F1 = Dateformat.getdateinstance ();
S1 = F1.format (today);
System.out.println ("dateformat.getdateinstance () = \ t" +s1);

F1 = Dateformat.getdateinstance (Dateformat.long,locale.china);
S1 = F1.format (today);
System.out.println ("dateformat.getdateinstance (Dateformat.long,locale.china) = \ T" + S1);

F1 = Dateformat.getdateinstance (Dateformat.medium,locale.china);
S1 = F1.format (today);
System.out.println ("dateformat.getdateinstance (Dateformat.medium,locale.china) = \ T" + S1);

F1 = Dateformat.getdateinstance (Dateformat.short,locale.china);
S1 = F1.format (today);
System.out.println ("dateformat.getdateinstance (Dateformat.short,locale.china) = \ T" + S1);

System.out.println ("\ n use DateFormat class to display various time formats");

Show various time formats
F1 = Dateformat.gettimeinstance ();
S1 = F1.format (today);
System.out.println ("dateformat.gettimeinstance () = \ t" +s1);

F1 = Dateformat.gettimeinstance (Dateformat.long,locale.china);
S1 = F1.format (today);
System.out.println ("dateformat.gettimeinstance (Dateformat.long,locale.china) = \ t" +s1);

F1 = Dateformat.gettimeinstance (Dateformat.medium,locale.china);
S1 = F1.format (today);
System.out.println ("dateformat.gettimeinstance (Dateformat.medium,locale.china) = \ t" +s1);

F1 = Dateformat.gettimeinstance (Dateformat.short,locale.china);
S1 = F1.format (today);
System.out.println ("dateformat.gettimeinstance (Dateformat.short,locale.china) = \ t" +s1);

System.out.println ("\ n Show Calendar related time usage");

now = Calendar.getinstance ();
Today = Now.gettime ();
System.out.println ("Calendar.getinstance (). getTime () = \ T" + today.tostring ());

}
}

The results of the program run are shown below:

Display the related usage of the date class
New Date () = Fri 13:29:32 CST 2003

Display various date formats with the DateFormat class
Dateformat.getdateinstance () = 2003-5-2
Dateformat.getdateinstance (Dateformat.long,locale.china) = May 2, 2003
Dateformat.getdateinstance (Dateformat.medium,locale.china) = 2003-5-2
Dateformat.getdateinstance (Dateformat.short,locale.china) = 03-5-2

Display various time formats with the DateFormat class
Dateformat.gettimeinstance () = 13:29:32
Dateformat.gettimeinstance (Dateformat.long,locale.china) = 01:29 P.M. 32 sec
Dateformat.gettimeinstance (Dateformat.medium,locale.china) = 13:29:32
Dateformat.gettimeinstance (Dateformat.short,locale.china) = 1:29

Show the calendar's relevant time usage
Calendar.getinstance (). GetTime () = Fri may 13:29:33 CST 2003

Reprint
The Java language Calendar (Calendar), date (date), and DateFormat (date format) Form a basic but very important part of the Java standard. Dates are a key part of business logic calculations. All developers should be able to calculate future dates, customize the display format of dates, and parse text data into date objects. We have written two articles, this is the first one, we will approximate the study date, date format, date resolution and date calculation.


We will discuss the following classes:

1, Concrete Class (and abstract class relative) Java.util.Date
2. Abstract class Java.text.DateFormat and a specific subclass of it, Java.text.SimpleDateFormat
3. Abstract class Java.util.Calendar and a specific subclass of it, Java.util.GregorianCalendar

A specific class can be instantiated, but an abstract class cannot. You must first implement a specific subclass of the abstract class.

The date class began to evolve from the Java Development Package (JDK) 1.0, when it contained only a few methods of acquiring or setting up parts of a date data, such as month, day, and year. These methods have now been criticized and have been transferred to the Calendar class, which we will discuss further in this article. This improvement is designed to better handle the internationalization format of date data. Just like in JDK 1.1, the Date class is really just a package class that contains a long integer that represents the number of milliseconds from GMT (Greenwich Mean Time) 1970, January 1 00:00:00, before or after that moment.


One, create a Date object

Let's look at a simple example that creates a Date object using the system's current date and time and returns a long integer. This time is often referred to as the system time of the Java Virtual Machine (JVM) host environment.
Import Java.util.Date;

public class DateExample1 {
public static void Main (string[] args) {
Get the System Date/time
Date date = new Date ();

System.out.println (Date.gettime ());
}
}

In Saturday, September 29, 2001, the afternoon is about 6:50, the above example shows the result on the system output device is 1001803809710. In this case, it is worth noting that we created a Date object using the date constructor, which does not accept any arguments. This constructor uses the System.currenttimemillis () method internally to get the date from the system.

Well, now we know how to get the number of milliseconds that have been going on since January 1, 1970. How can we display this date in a user-aware format? Here the class Java.text.SimpleDateFormat and its abstract base class Java.text.DateFormat come in handy.


II. custom format for date data

If we want to customize the format of date data, for example Saturday-September-29th-2001. The following example shows how to do the work:

Import Java.text.SimpleDateFormat;
Import Java.util.Date;

public class DateExample2 {

public static void Main (string[] args) {

SimpleDateFormat Bartdateformat =
New SimpleDateFormat ("eeee-mmmm-dd-yyyy");

Date date = new Date ();

System.out.println (Bartdateformat.format (date));
}
}

As long as you pass the format string "eee-mmmm-dd-yyyy" to the SimpleDateFormat constructor, we can specify the format we want. You should be able to see that the ASCII characters in the format string tell the Format function which part of the date data is displayed below. Eeee is the week, MMMM is the month, DD is the day, YYYY is the year. The number of characters determines how the date is formatted. Passing "Ee-mm-dd-yy" displays sat-09-29-01. Please see Sun's Web site for full instructions on getting the date formatting options.


Iii. parsing text data into date objects

Suppose we have a text string that contains a formatted date object, and we want to parse the string and create a Date object from the text date data. We will again call the SimpleDateFormat class with the formatted string "MM-DD-YYYY", but this time we use format parsing instead of generating a text date data. Our example, shown below, will parse the text string "9-29-2001" and create a Date object with a value of 001736000000.

Example program:

Import Java.text.SimpleDateFormat;
Import Java.util.Date;

public class DateExample3 {

public static void Main (string[] args) {
Create a date formatter that can parse dates of
The form mm-dd-yyyy.
SimpleDateFormat Bartdateformat =
New SimpleDateFormat ("mm-dd-yyyy");

Create A string containing a text date to be parsed.
String datestringtoparse = "9-29-2001";

try {
Parse the text version of the date.
We have to perform the parse method in a
Try-catch construct in case Datestringtoparse
Does not contain a date in the format we are expecting.
Date date = Bartdateformat.parse (Datestringtoparse);

Now send the parsed date as a Long value
to the system output.
System.out.println (Date.gettime ());
}
catch (Exception ex) {
System.out.println (Ex.getmessage ());
}
}
}


V. Using the standard date formatting process

Now that we can generate and parse custom date formats, let's take a look at how to use the built-in formatting process. Method Dateformat.getdatetimeinstance () allows us to obtain the standard date formatting process in several different ways. In the following example, we obtained four built-in date formatting processes. They include a short, medium, long, and full date format.

Import Java.text.DateFormat;
Import Java.util.Date;

public class DateExample4 {

public static void Main (string[] args) {
Date date = new Date ();

DateFormat Shortdateformat =
Dateformat.getdatetimeinstance (
Dateformat.short,
Dateformat.short);

DateFormat Mediumdateformat =
Dateformat.getdatetimeinstance (
Dateformat.medium,
Dateformat.medium);

DateFormat Longdateformat =
Dateformat.getdatetimeinstance (
Dateformat.long,
Dateformat.long);

DateFormat Fulldateformat =
Dateformat.getdatetimeinstance (
Dateformat.full,
Dateformat.full);

System.out.println (Shortdateformat.format (date));
System.out.println (Mediumdateformat.format (date));
System.out.println (Longdateformat.format (date));
System.out.println (Fulldateformat.format (date));
}
}



Note that we have passed two values in each call to Getdatetimeinstance. The first parameter is a date style, and the second parameter is the time style. They are all basic data type int (integer type). For readability, we used the constants provided by the DateFormat class: Short, MEDIUM, LONG, and full. To know more methods and options for getting the time and date formatting process, see the explanation on the Sun Company web site.

When running our example program, it will output the following content to the standard output device:
9/29/01 8:44 PM
SEP, 2001 8:44:45 PM
September, 2001 8:44:45 PM EDT
Saturday, September, 2001 8:44:45 PM EDT


Vi. Calendar Class

We are now able to format and create a Date object, but how can we set and get a specific part of the date data, such as hours, days, or minutes? How do we add or subtract values from these parts of the date? The answer is to use the Calendar class. As we mentioned earlier, the methods in the Calendar class replace the reviled methods in the date class.

Suppose you want to set, get, and manipulate the various parts of a Date object, such as a one-month day or a one-week day. To demonstrate this process, we will use the specific subclass Java.util.GregorianCalendar. Consider the following example, which calculates that the following tenth Friday is number 13th.

Import Java.util.GregorianCalendar;
Import Java.util.Date;
Import Java.text.DateFormat;

public class DateExample5 {

public static void Main (string[] args) {
DateFormat DateFormat =
Dateformat.getdateinstance (Dateformat.full);

Create our Gregorian Calendar.
GregorianCalendar cal = new GregorianCalendar ();

Set the date and time of our calendar
To the system ' s date and time
Cal.settime (New Date ());

System.out.println ("System Date:" +
Dateformat.format (Cal.gettime ()));

Set the day's week to FRIDAY
Cal.set (Gregoriancalendar.day_of_week,
Gregoriancalendar.friday);
System.out.println ("After Setting day of Week to Friday:" +
Dateformat.format (Cal.gettime ()));

int friday13counter = 0;
while (Friday13counter <= 10) {

Go to the next Friday by adding for 7 days.
Cal.add (Gregoriancalendar.day_of_month, 7);

If the day of month is, we have
Another Friday the 13th.
if (Cal.get (gregoriancalendar.day_of_month) = = 13) {
friday13counter++;
System.out.println (Dateformat.format (Cal.gettime ()));
}
}
}
}



In this example we make an interesting function call:
Cal.set (Gregoriancalendar.day_of_week,
Gregoriancalendar.friday);

And:
Cal.add (Gregoriancalendar.day_of_month, 7);

The Set method allows us to adjust our time to Friday by simply setting which day of the week the domain will be. Notice here that we use constants Day_of_week and Friday to enhance the readability of the code. The Add method allows us to add a value to a date. All complex calculations of the year are handled automatically by this method.

The output of our example is:
System Date:saturday, September 29, 2001
When we set it to Friday, it became: Friday, September 28, 2001
Friday, September 13, 2002
Friday, December 13, 2002
Friday, June 13, 2003
Friday, February 13, 2004
Friday, August 13, 2004
Friday, May 13, 2005
Friday, January 13, 2006
Friday, October 13, 2006
Friday, April 13, 2007
Friday, July 13, 2007
Friday, June 13, 2008


Seven, time in your hands

With these examples of the Date and calendar classes, you should be able to create many methods using Java.util.Date, Java.text.SimpleDateFormat, and Java.util.GregorianCalendar.

Calendar Date Object in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.