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