Some methods of Java datetime operations

Source: Internet
Author: User

1. Get the Calendar instance:

Calendar C = calendar.getinstance ();

2. Define the date/time format:

SimpleDateFormat SDF =new simpledateformat ("Yyyy-mm-dd HH:mm:ss");

3. Convert the date/time to a fixed format using the SimpleDateFormat format () method:

= Sdf.format (C.gettime ());

4. Convert the string to date/time using SimpleDateFormat's Parse () method:

Date d = sdf3.parse ("2016-08-08 16:43:00");

5. Date/time increase, decrease, use the calendar's Add () method, such as reducing the date by 100 days:

C.add (calendar.date,-100);

6. Date/Time settings, using the calendar's set () method, such as setting the hour to 0 o'clock:

C.set (calendar.hour_of_day, 0);

Example:

 PackageMyCalendar;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;ImportJava.util.Calendar;Importjava.util.Date; Public classMyCalendar { Public Static voidMain (String args[])throwsexception{Calendar C=calendar.getinstance (); SimpleDateFormat SDF1=NewSimpleDateFormat ("YyyyMMdd"); SimpleDateFormat SDF2=NewSimpleDateFormat ("Hhmmss"); SimpleDateFormat sdf3=NewSimpleDateFormat ("Yyyymmddhhmmss"); SimpleDateFormat SDF4=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String Date=Sdf1.format (C.gettime ());        SYSTEM.OUT.PRINTLN (date); String Time=Sdf2.format (C.gettime ());                System.out.println (time); String DT= "20160808162405"; Date D=sdf3.parse (DT); DT=Sdf4.format (d);        C.settime (d); C.add (Calendar.date,-100); C.set (Calendar.hour_of_day,0); C.set (Calendar.minute,0); C.set (Calendar.second,0); System.out.println ("100 days ago:" +Sdf4.format (C.gettime ())); C.add (Calendar.date,200); C.set (Calendar.hour_of_day,0); C.set (Calendar.minute,0); C.set (Calendar.second,0); System.out.println ("100 Days later:" +Sdf4.format (C.gettime ())); }}

The results of the operation are as follows:

Some methods of Java datetime operations

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.