[Reprinted] Date Processing in Java [date addition and subtraction]

Source: Internet
Author: User

 

(1) obtain the current date:

    Java. util.CalendarCalendar = java. util.Calendar. getinstance ();

                             Or= New java. util.Gregoriancalendar ();

 

 

(2) add or subtract several days from the CDR Date:

    Function prototype: void java. util. Calendar. Add (INT field, int amount );

    Add 5 days: Calendar.Add(Java. util. Calendar.Date, 5 );

     Minus 5 days: Calendar.Add(Java. util. Calendar.Date,-5 );

 

(3) obtain the date object corresponding to the CDR:

   Java. util. DateDate = calendar. gettime ();

 

(4) date comparison:

   Boolean java. util. Calendar.Before(Object when );

   Boolean java. util. Calendar.After(Object when );

    IntJava. util. Calendar.Compareto(Calendar anothercalendar );

 

   Java. util. Date.Before(Java. util. Date anotherdate );

   Java. util. Date.After(Java. util. Date anotherdate );

   Int java. util. Date.Compareto(Java. util. Date anotherdate );

 

(5) Date Format:

   Java. Text. simpledateformat SDF = new java. Text.Simpledateformat (); // Use the default format

                       Or specify the format = new java. Text.Simpledateformat ("yyyy-mm-dd ");

                        Another example:

                            = New java. Text.Simpledateformat ("HH: mm: SS ");

                            = New java. Text.Simpledateformat ("yyyy-mm-dd
Hh: mm: SS ");

                      

   Java. Lang.StringJava. Text. dateformat.Format(Java. util.DateDate)

   Example: system. Out. println (SDF. Format (date ));

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.