Java time, java time formatting

Source: Internet
Author: User

Java time, java time formatting

Calendar. getInstance (). getTime () Get the current Time (including the week and Time Zone CST China Standard Time): Fri Jan 06 21:03:36 CST 2017

Calendar cal = Calendar. getInstance ();

The current date and time are displayed in full:

Method 1:
DateFormat fmtDateTime = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss ");
System. out. println (fmtDateTime. format (new Date ()));
Output: 21:19:02

 

Method 2:

Cal. setTime (new Date ());

System. out. println (fmtDateTime. format (cal. getTime ()));

Output: 23:41:00

 

Show year:

Calendar cal = Calendar. getInstance ();

System. out. println (cal. get (Calendar. YEAR ));

Output: 2017

Show month: Starting from 0, add 1

System. out. println (cal. get (Calendar. MONTH) + 1 );

 

Cal. get (Calendar. MINUTE) or cal. get (Calendar. HOUR_OF_DAY) outputs the int type.

One hour later:

Method 1:

System. out. println (cal. get (Calendar. HOUR_OF_DAY) + 1 );

Method 2: changed the value of HOUR_OF_DAY:

Cal. add (Calendar. HOUR_OF_DAY, 1 );
System. out. println (cal. get (Calendar. HOUR_OF_DAY ));

 

6 minutes ago (if the current time is23:32:39):

Method 1:

System. out. println (cal. get (Calendar. MINUTE)-6 );

Method 2:

Cal. add (Calendar. MINUTE,-6 );
Int minute = cal. get (Calendar. MINUTE );
System. out. println (minute );

Output: 26

 

String time1 = fmtDateTime. format (cal. getTime ());
System. out. println (time1 );

Output: 23:26:39

 

Compare two times:

Calendar cal = Calendar. getInstance ();

Calendar cal2 = Calendar. getInstance ();

Cal2.add (Calendar. HOUR, 7); // The second time is 7 hours later.

System. out. println (cal. compareTo (cal2); // cal is smaller than cal2 and outputs-1.

Calculate the two time difference:

Long min = cal2.getTimeInMillis ()-cal. getTimeInMillis (); // subtle
Long diffHour = min/(1000*60*60); // converts to hour
System. out. println (diffHour); // output 7

 

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.