Date class: (Class under the Java.util package)
1. How do I format an object of the date class to display the date as a custom format?
PackageCom.zhaixiaobin.jobText.demo1;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;Importjava.util.Date; Public classDemo01 { Public Static voidMain (string[] args)throwsParseException {/** The date class under Java.util, showing the current time*/Date Date=NewDate (); SYSTEM.OUT.PRINTLN (date); /** Use SimpleDateFormat class to format time, user-defined format*/System.out.println (); SimpleDateFormat SDF1=NewSimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"); SimpleDateFormat SDF2=NewSimpleDateFormat ("Yyyy/mm/dd hh:mm:ss"); SimpleDateFormat sdf3=NewSimpleDateFormat ("yyyy mm month dd Day hh mm min ss sec"); String str1=Sdf1.format (date); String str2=Sdf2.format (date); String STR3=Sdf3.format (date); System.out.println (STR1); System.out.println (STR2); System.out.println (STR3); System.out.println (); /** Use the Parse method to display the string as a date*/String str= "2015-6-9 21:19:30"; SimpleDateFormat SDF=NewSimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"); Date Now=sdf.parse (str); System.out.println (now); }}
Output Result :
Wed June 10:32:08 CST 20162016-06-29 10:32:082016/06/29 10:32:082016 June 29 10:32 08 sec Tue June 21:19:30 CST 2015
Now generally tend to use the Calendar class
Calendar class (class under the Java.util package)
1> how to get an object of the Calendar class and get the year, month, day, time, minute, second
Use the getinstance () method to get a calendar object
Package Com.zhaixiaobin.jobtext.demo1;import Java.util.calendar;public class Demo02 {public static void main ( String[] args) {Calendar c=calendar.getinstance (); Create a Calendar object int year=c.get (calendar.year); int Month=c.get (calendar.month) +1; //0 means January, so add 1 int Day=c.get (calendar.day_of_month); int Hour=c.get (calendar.hour_of_day); int Minute=c.get (calendar.minute); int Second=c.get (calendar.second); System.out.println ("Now is:" +year+ "year" +month+ "month" +day+ "Day" + "+hour+" when " +minute+" cent "+second+" seconds ");}}
Output Result:
Now is: June 29, 2016 10:51 16 seconds
2> since both the date class and the Calendar class can display the current date, how do you convert the date class and the Calendar class?
Package Com.zhaixiaobin.jobtext.demo1;import Java.text.simpledateformat;import Java.util.calendar;import Java.util.date;public class Demo03 {public static void main (string[] args) {Calendar c1=calendar.getinstance ();D ate Date2=c1.gettime ();
Long time =c1.gettimeinmills ()//Gets the C1 value, in milliseconds SimpleDateFormat sdf5=new simpledateformat ("Yyyy-mm-dd hh:mm:ss"); String Now=sdf5.format (date2); System.out.println ("Now is:" +now);
System.out.println ("Now is:" +time+ "seconds");
} }
Output Result:
Now is: 2016-06-29-11:00:50
Now is: 1,467,169,495,364 seconds
Java Date operation