Application of Calendar class
The most important role of the date class is to get the current time, while the class also has set time and some other functions, but because of its own design problems, these methods have been criticized many, not recommended, it is recommended to use the Calendar class for time and date processing.
The Java.util.Calendar class is an abstract class that can get a Calendar object by calling the getinstance () static method, which is initialized by the current datetime, which means the current time by default, such as Calendar C = Calendar.getinstance ();
So how do you use Calendar to get information about the year, month, day, time, and more? Let's look at the following code:
Where you call the getinstance () method of the Calendar class to get an instance , and then get the datetime information by calling the Get () method, the parameter is the value of the field that needs to be obtained, calendar.year, and so on as the calendar Static constants defined in the class.
Operation Result:
The Calendar class provides the GetTime () method for getting the date object, completing the conversion of the calendar and date, and the Gettimeinmillis () method to get the time value of this calendar, in milliseconds. As shown below:
Operation Result:
Example:
Implements the time to get the Calendar object and convert it to the specified format
1 ImportJava.text.SimpleDateFormat;2 ImportJava.util.Calendar;3 Importjava.util.Date;4 5 Public classHelloWorld {6 7 Public Static voidMain (string[] args) {8 //Create a Canlendar object9Calendar C =calendar.getinstance ();Ten One //convert a Calendar object to a Date object ADate Date =c.gettime (); - - //Create a SimpleDateFormat object that specifies the destination format theSimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); - - //converts a date to a string of the specified format -String now =Sdf.format (date); +System.out.println ("Current time:" +Now ); - } +}
Output Result:
Current time: 2016-03-31-08:08:33
Java Foundation: Application of the Calendar class (better than Date Class)