The time operations in Java are all four cases: get the current time, get a certain format of a time, set the time and time of the operation.
1. Get the current time
There are two ways to get, first, to use the Java.util.Date class.
Date date = new Date ();
Date.gettime ();
There is also a way to use System.currenttimemillis ();
Both of these methods get the same result, which is the millisecond value of the long time of the current time, which is actually the number of milliseconds between the current time value and 0 minutes and 0 seconds from zero January 1, 1970.
2. Get a certain format for a certain time
To get the format of the time, you need to use a class Java.text.SimpleDateFormat that is dedicated to the time format.
First, define a SimpleDateFormat variable
private static SimpleDateFormat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
String myData = Df.format (New Date ());
3. Set the time
Now set the time, it is recommended to use the Java.util.Calendar class to operate, because many methods of the Java.util.Date class are obsolete, the Calendar class has a lot of overloaded setting time method. We can set it for one item, or we can make many settings at the same time.
public void set (int field, int value) sets the given Calendar field to the given value.
Public final void Set (int year, int month, int date) sets YEAR MONTH DAY_OF_MONTH the value of the Calendar field, and. Keep the previous values for the other calendar fields.
Public final void Set (int year, int month, int date, int hourofday, int minute) sets YEAR MONTH DAY_OF_MONTH HOUR_OF_DAY MINUTE The value of the Calendar field,,, and. Keep the previous values of the other fields.
Public final void Set (int year, int month, int date, int hourofday, int minute, int second) Set field YEAR , MONTH , DAY_OF_MONTH , MINUTE SECOND The value of/>, and. Keep the previous values of the other fields.
4. Time arithmetic
public abstract void Add (int field, int amount) Adds or subtracts a specified amount of time for a given calendar field, based on the rules of the calendar.
For example, to subtract 5 days from the current calendar time.add(Calendar.DAY_OF_MONTH, -5);
CalendarObjectReturns the judging result after the time represented.
CalendarObjectReturns the judging result before the time is expressed.
Java Learning (11): Common time operations in Java