How to Use the Date and Calendar classes in Java

Source: Internet
Author: User
Tags date1 dateformat
. Calculate the maximum number of days of a month

Calendar time = Calendar. getInstance ();
Time. clear ();
Time. set (Calendar. YEAR, year); // year is int
Time. set (Calendar. MONTH, I-1); // note that the Calendar Object is 0 by default
Int day = time. getActualMaximum (Calendar. DAY_OF_MONTH); // number of days of the current month
Note: before using the set method, you must clear it first. Otherwise, many information will inherit from the current system time.

2. Conversion of Calendar and Date

(1) convert Calendar to Date
Calendar cal = Calendar. getInstance ();
Date date = cal. getTime ();

(2) convert Date to Calendar
Date date = new Date ();
Calendar cal = Calendar. getInstance ();
Cal. setTime (date );

3. format the output date and time (this is usually used)

Date date = new Date ();
SimpleDateFormat df = new SimpleDateFormat ("yyyy-MM-dd hh: mm: ss ");
String time = df. format (date );
System. out. println (time );

4. Calculate the week of the year

(1) Calculate the week number of a day in a year.
Calendar cal = Calendar. getInstance ();
Cal. set (Calendar. YEAR, 2006 );
Cal. set (Calendar. MONTH, 8 );
Cal. set (Calendar. DAY_OF_MONTH, 3 );
Int weekno = cal. get (Calendar. WEEK_OF_YEAR );

(2) calculate the number of weeks in a 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

5. add () and roll () usage (not commonly used)

(1) add () method
SimpleDateFormat df = new SimpleDateFormat ("yyyy-MM-dd ");
Calendar cal = Calendar. getInstance ();
Cal. set (Calendar. YEAR, 2006 );
Cal. set (Calendar. MONTH, 8 );
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, 8 );
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-0
2006-0
It can be seen that the roll () method loops over the current month, and the add () method is generally used;

6. Calculate the number of days between two arbitrary periods (this is usually used)
(1) upload to the Calendar Object
Public int getIntervalDays (Calendar startday, Calendar endday )...{
If (startday. after (endday ))...{
Calendar cal = startday;
Startday = endday;
Endday = cal;
}
Long sl = startday. getTimeInMillis ();
Long el = endday. getTimeInMillis ();

Long ei = el-sl;
Return (int) (ei/(1000*60*60*24 ));
}
(2) input Date object

Public int getIntervalDays (Date startday, Date endday )...{
If (startday. after (endday ))...{
Date cal = startday;
Startday = endday;
Endday = cal;
}
Long sl = startday. getTime ();
Long el = endday. getTime ();
Long ei = el-sl;
Return (int) (ei/(1000*60*60*24 ));
}
(3) improved methods for accurate calculation of days separated
Public int getDaysBetween (Calendar d1, Calendar d2 )...{
If (d1.after (d2 ))...{
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); // obtain the actual number of days of the current year.
D1.add (Calendar. YEAR, 1 );
} While (d1.get (Calendar. YEAR )! = Y2 );
}
Return days;
}
Note: The above method can be used to derive any time, for example, to find the email received within three weeks (get the current system time-then get the time three weeks ago) it is best to compare the received time with the long time.
For example, the date 1 year ago (pay attention to millisecond conversion)
Java. util. Date myDate = new java. util. Date ();
Long myTime = (myDate. getTime ()/1000)-60*60*24*365;
MyDate. setTime (myTime * 1000 );
String mDate = formatter. format (myDate );

7. Conversion between String, Date, and Long (most commonly used)

Convert a string to a time type (the string can be of any type, as long as it is consistent with the format in SimpleDateFormat)
When we take the time span, substring will issue the specific time -- long-Comparison

Java. text. SimpleDateFormat sdf = new java. text. SimpleDateFormat ("M/dd/yyyy hh: mm: ss a", java. util. Locale. US );
Java. util. Date d = sdf. parse ("5/13/2003 10:31:37 AM ");
Long dvalue = d. getTime ();
SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss ");
String mDateTime1 = formatter. format (d );

8. Calculate the time by Time

Year, month, week, and date
SimpleDateFormat formatter2 = new SimpleDateFormat ("yyyy-mm f e ");
Java. util. Date date2 = formatter2.parse ("Friday 2003-05 ");
SimpleDateFormat formatter3 = new SimpleDateFormat ("yyyy-MM-dd ");
String mydate2 = formatter3.format (date2 );

The day of the week.
Mydate = myFormatter. parse ("2001-1-1 ");
SimpleDateFormat formatter4 = new SimpleDateFormat ("E ");
String mydate3 = formatter4.format (mydate );

9. java and specific database integration

In developing web applications, for different database date types, we need to convert the date types in our programs. If the corresponding database data is of the oracle Date type, that is, only the year, month, and day are required, you can select java. SQL. date type. if it corresponds to the DateTime type of the MSsqlserver database, that is, year, month, day, hour, minute, and second, select java. SQL. timestamp type
You can use dateFormat to define the time and date format and convert it to a string.

Class Datetest {
* Method converts a string-type date to a timestamp (Timestamp java. SQL. timestamp)
* @ Param dateString the string to be converted to timestamp
* @ Return dataTime timestamp

Public final static java. SQL. Timestamp string2Time (String dateString)
Throws java. text. ParseException {
DateFormat dateFormat;
DateFormat = new SimpleDateFormat ("yyyy-MM-dd kk: mm: ss. SSS", Locale. ENGLISH); // set the format
// DateFormat = new SimpleDateFormat ("yyyy-MM-dd kk: mm: ss", Locale. ENGLISH );
DateFormat. setLenient (false );
Java. util. Date timeDate = dateFormat. parse (dateString); // util type
Java. SQL. Timestamp dateTime = new java. SQL. Timestamp (timeDate. getTime (); // type of Timestamp, timeDate. getTime () returns a long type
Return dateTime;
}

* Method converts a string-type Date to a Date (java. SQL. Date)
* @ Param dateString the string to be converted to Date
* @ Return dataTime Date

Public final static java. SQL. Date string2Date (String dateString)
Throws java. lang. Exception {
DateFormat dateFormat;
DateFormat = new SimpleDateFormat ("yyyy-MM-dd", Locale. ENGLISH );
DateFormat. setLenient (false );
Java. util. Date timeDate = dateFormat. parse (dateString); // util type
Java. SQL. Date dateTime = new java. SQL. Date (timeDate. getTime (); // SQL type
Return dateTime;
}

Public static void main (String [] args ){
Date da = new Date ();
Note: da. getTime () obtains a long value.
System. out. println (da. getTime ());

Convert from date to timestamp

Method 1: Use new Timestamp (long)
Timestamp t = new Timestamp (new Date (). getTime ());
System. out. println (t );

Method 2: Use Timestamp (int year, int month, int date, int hour, int minute, int second, int nano)
Timestamp tt = new Timestamp (Calendar. getInstance (). get (
Calendar. YEAR)-1900, Calendar. getInstance (). get (
Calendar. MONTH), Calendar. getInstance (). get (
Calendar. DATE), Calendar. getInstance (). get (
Calendar. HOUR), Calendar. getInstance (). get (
Calendar. MINUTE), Calendar. getInstance (). get (
Calendar. SECOND), 0 );
System. out. println (tt );

Try {
String sToDate = "2005-8-18"; // String used for conversion to java. SQL. Date
String sToTimestamp = "14:21:12. 123"; // String used for conversion to java. SQL. Timestamp
Date date1 = string2Date (sToDate );
Timestamp date2 = string2Time (sToTimestamp );
System. out. println ("Date:" + date1.toString (); // The result is displayed.
System. out. println ("Timestamp:" + date2.toString (); // The result is displayed.
} Catch (Exception e ){
E. printStackTrace ();
}
}
}

Related Article

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.