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 static constant defined in the Calendar 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:
Task Demo:
//Create a Canlendar objectCalendar C =calendar.getinstance (); //convert a Calendar object to a Date objectDate Date =C.gettime (); //Create a SimpleDateFormat object that specifies the destination formatSimpleDateFormat SDF =NewSimpleDateFormat ("YYYY-MM-DD HH:mm:ss"); //converts a date to a string of the specified formatString now =Sdf.format (date); System. out. println ("Current Time:"+Now );
Operation Result:
Application of Java Learning--calendar class