1. Overview of dates in Java <br />Date is a very complex piece of content in Java. For a date in different language and country environments, the internationalization of dates, the conversion between dates and time, the addition and subtraction of dates, and the display format of dates are all very complicated issues.
In Java, the operation date mainly involves the following classes:
1. java.util.Date
Class Date represents a specific moment, accurate to milliseconds. Starting with JDK 1.1, the Calendar class should be used to implement conversion between date and time fields, and the DateFormat class should be used to format and analyze date strings. The method in Date to interpret dates as year, month, day, hour, minute, and second values is abandoned.
2. java.text.DateFormat (abstract class)
DateFormat is an abstract class of date/time formatting subclasses that format and analyze dates or times in a language-independent manner. Date/time formatting subclasses (such as SimpleDateFormat) allow formatting (i.e. date->text), analysis (text->date), and standardization. Denote the date as a Date object, or as the number of milliseconds starting from the moment GMT (GMT) 1970, January 1, 00:00:00.
3. java.text.SimpleDateFormat (DateFormat direct subclass)
SimpleDateFormat is a specific class that formats and analyzes dates in a locale-related way. It allows formatting (date->text), analysis (text->date), and normalization.
SimpleDateFormat enables you to select any user-defined date-time format mode. However, it is still recommended to use getTimeInstance, getDateInstance, or getDateTimeInstance in DateFormat to create a new date-time formatter.
4. java.util.Calendar (abstract class)
The Calendar class is an abstract class that provides some methods for converting a specific moment to a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, etc., and provides some methods for manipulating calendar fields such as getting the date of the next week. The instant can be expressed as a millisecond value, which is the offset from the epoch (i.e., 00:00:00.000, GMT, January 1, 1970, GMT).
Like other locale-sensitive classes, Calendar provides a class method getInstance to obtain a common object of this type. Calendar's getInstance method returns a Calendar object whose calendar fields have been initialized by the current date and time.
5. java.util.GregorianCalendar (direct subclass of Calendar)
GregorianCalendar is a concrete subclass of Calendar that provides a standard calendar system used by most countries in the world.
GregorianCalendar is a hybrid calendar that supports both the Julian and Gregorian calendar systems with the support of a single discontinuity, which by default corresponds to the Gregorian date when the Gregorian calendar was founded (some countries were founded on October 15, 1582, and later in others). The start date can be changed by the caller by calling setGregorianChange().
2. Use of java.util.Date
1. Introduction to the API of java.util.Date
The class java.util.Date represents a specific moment, accurate to milliseconds. There are many methods provided, but many are outdated and are not recommended. The following lists only methods that are not outdated:
Summary of construction methods
----------------------
Date()
Assign a Date object and initialize this object with the current time to indicate the time it was allocated (accurate to milliseconds).
Date(long date)
Assign a Date object and initialize this object to represent the specified number of milliseconds since the standard benchmark time (called "epoch", that is, 00:00:00 GMT on January 1, 1970).
Method Summary
----------------------
boolean after(Date when)
Tests whether this date is after the specified date.
boolean before(Date when)
Tests whether this date is before the specified date.
Object clone()
Returns a copy of this object.
int compareTo(Date anotherDate)
Compare the order of two dates.
boolean equals(Object obj)
Compare the equality of two dates.
long getTime()
Returns the number of milliseconds represented by this Date object since January 1, 1970 00:00:00 GMT.
int hashCode()
Returns the hash code value of this object.
void setTime(long time)
Set this Date object to represent the time point in time milliseconds after 00:00:00 GMT on January 1, 1970.
String toString()
Convert this Date object to String of the following form: dow mon dd hh:mm:ss zzz yyyy where:
dow is one day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
mon is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
dd is a day in January (01 to 31) displayed as a two-digit decimal number.
hh is the hour of the day (00 to 23), displayed as a two-digit decimal number.
mm is the minutes (00 to 59) in the hour and is displayed as a two-digit decimal number.
ss is the number of seconds (00 to 61) in a minute, displayed as a two-digit decimal number.
zzz is the time zone (and reflects daylight saving time). The standard time zone abbreviation includes the time zone abbreviation recognized by method parse. If time zone information is not provided, zzz is empty, i.e. no characters are included at all.
yyyy is a year, displayed as a 4-digit decimal number.
Here is a comprehensive example of the Date class:
public class TestDate { public static void main(String[] args) { TestDate testdate = new TestDate(); testdate.getSystemCurrentTime(); testdate.getCurrentDate(); } /** * Get the current system time* System.currentTimeMillis() returns the current system time, and the result starts at 0:00:00 on January 1, 1970. The number of milliseconds elapsed until the program execution and obtaining the system time* 1 second = 1000 milliseconds*/ public void getSystemCurrentTime(){ System.out.println("---get the current system time---"); System.out.println(System.currentTimeMillis()); } public void getCurrentDate(){ System.out.println("---get the current time of the system---"); //Create and initialize a date (the initial value is the current date) Date date = new Date(); System.out.println("The current date is = " + date.toString()); System.out.println("The number of milliseconds experienced since January 1, 1970 = " + date.getTime()); }} 2. Use of java.text.DateFormat abstract class
DateFormat is an abstract class of date/time formatting subclasses that format and analyze dates or times in a language-independent manner. Date/time formatting subclasses (such as SimpleDateFormat) allow formatting (i.e. date->text), analysis (text->date), and standardization. Denote the date as a Date object, or as the number of milliseconds starting from the moment GMT (GMT) 1970, January 1, 00:00:00.
DateFormat provides a number of class methods to get default date/time Formatter based on default or given locale and multiple formatting styles. Format styles include FULL, LONG, MEDIUM and SHORT. More details and examples of using these styles are provided in the method description.
DateFormat helps format and analyze dates for any locale. For months, weeks, and even calendar formats (lunar and solar calendar), the code can be completely irrelevant to locale conventions.
To format a date in the current locale, use a static factory method:
myString = DateFormat.getDateInstance().format(myDate);
If you format multiple dates, it is more efficient to get the format and use it multiple times, so that the system does not have to obtain information about the environment language and national agreements multiple times.
DateFormat df = DateFormat.getDateInstance(); for (int i = 0; i < myDate.length; ++i) { output.println(df.format(myDate[i]) + "; "); }
To format the dates of different locales, specify it in the call to getDateInstance().
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
DateFormat can also be used for analysis.
myDate = df.parse(myString);
Use getDateInstance to get the standard date format for that country. Some other static factory methods are also provided. Use getTimeInstance to get the time format for that country. Use getDateTimeInstance to get date and time formats. Different options can be passed into these factory methods to control the length of the result (from SHORT to MEDIUM to LONG to FULL). The exact result depends on the locale, but usually:
SHORT is completely a number, such as 12.13.52 or 3:30pm
MEDIUM is longer, such as Jan 12, 1952
LONG is longer, such as January 12, 1952 or 3:30:32pm
FULL is fully specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.
If you like, you can also set the time zone on the format. If you want to impose more control on formatting or analysis (or give the user more control), you can try casting the DateFormat obtained from the factory method to SimpleDateFormat. This works for most countries; just remember to put it in a try block in case of special formats.
You can also use the analysis and formatting method with ParsePosition and FieldPosition to analyze parts of a string step by step. Align any specific field, or find out where the string is selected on the screen.
DateFormat is not synchronous. It is recommended to create independent format instances for each thread. If multiple threads access a format at the same time, it must remain externally synchronized.
3. Use of java.text.SimpleDateFormat (DateFormat direct subclass)
SimpleDateFormat is a specific class that formats and analyzes dates in a locale-related way. It allows formatting (date->text), analysis (text->date), and normalization.
SimpleDateFormat enables you to select any user-defined date-time format mode. However, it is still recommended to use getTimeInstance, getDateInstance, or getDateTimeInstance in DateFormat to create a new date-time formatter. Each such class method can return a date/time formatter initialized in the default format mode. The format pattern can be modified using the applyPattern method as needed. For more information on using these methods, see DateFormat.
Date and time mode
The date and time format is specified by the date and time pattern string. In date and time pattern strings, unquoted letters 'A' to 'Z' and 'a' to 'z' are interpreted as pattern letters to represent date or time string elements. Text can be enclosed in single quotes (') to avoid explanation. "''" means single quotes. All other characters are not interpreted; they are simply copied to the output string when formatted, or matched to the input string when analyzed.
For more reference information, you can view the JDK API documentation. Here is a comprehensive example:
public class TestDateFormat { public static void main(String[] args) throws ParseException { TestDateFormat tdf = new TestDateFormat(); tdf.dateFormat(); } /** * Test the SimpleDateFormat class* @throws ParseException */ public void dateFormat() throws ParseException{ //Create date Date date = new Date(); //Create different date formats DateFormat df1 = DateFormat.getInstance(); DateFormat df2 = new SimpleDateFormat("yyyy-MM-01 hh:mm:ss EE"); DateFormat df3 = DateFormat.getDateInstance(DateFormat.FULL, Locale.CHINA); //Create a date format with a specified length of the specified country. The length is different, and the date integrity displayed is also different. DateFormat df4 = new SimpleDateFormat("yyyyy year MM month dd day hh hour mm minute ss seconds EE", Locale.CHINA); DateFormat df5 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss EEEEEE", Locale.US); DateFormat df6 = new SimpleDateFormat("yyyy-MM-dd"); //Output dates in different formats System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- df3.format(date)); System.out.println("According to the specified format yyyyy year month dd day hh hour mm minute ss seconds EE, the area is Chinese: " + df4.format(date)); System.out.println("According to the specified format yyyy-MM-dd hh:mm:ss EE, the area is United States: " + df5.format(date)); System.out.println("According to the specified format yyyy-MM-dd, the system default area: " + df6.format(date)); //Convert strings that meet this format to date. If the format does not match, an error will occur Date date1 = df1.parse("16-01-24 2:32 pm"); Date date2 = df2.parse("2016-01-24 02:51:07 Sunday"); Date date3 = df3.parse("2016-01-24"); Date date4 = df4.parse("2016-01-24 02:51:18 Sunday"); Date date6 = df6.parse("2016-01-24"); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- System.out.println(date1); System.out.println(date2); System.out.println(date3); System.out.println(date4); System.out.println(date5); System.out.println(date6); }} 4. java.util.Calendar (abstract class)
java.util.Calendar is an abstract class, an abstract representation of system time. It provides some methods for converting a specific moment to a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, etc., and provides some methods for manipulating calendar fields (such as getting the date of the next week). The instant can be expressed as a millisecond value, which is the offset from the epoch (i.e., 00:00:00.000, GMT, January 1, 1970, GMT).
Like other locale-sensitive classes, Calendar provides a class method getInstance to obtain a common object of this type. Calendar's getInstance method returns a Calendar object whose calendar fields have been initialized by the current date and time.
An instance of Calendar is an abstract representation of system time. From the instance of Calendar, you can know information such as year, month, day, week, month, and month. There is a static method get(int x) in the Calendar class. Through this method, you can get some values (year, month, day, week, month, etc.) information of the relevant instance. Parameter x is a yield value, defined in Calendar.
Some traps in Calendar can easily fall:
1. Calendar's week starts on Sunday, with a constant value of 0.
2. Calendar's month starts from January, with a constant value of 0.
3. Calendar's first day of each month is 1.
5. java.util.GregorianCalendar (direct subclass of Calendar)
GregorianCalendar is a concrete subclass of Calendar that provides a standard calendar system used by most countries in the world. Used in conjunction with Calendar abstract class.
Here is a comprehensive example to see the usage of the Calendar class:
public class TestCalendar { public static void main(String[] args) throws ParseException { TestCalendar testCalendar = new TestCalendar(); testCalendar.testCalendar(); testCalendar.testCalendar2(); } public void testCalendar(){ //How to create Calendar Calendar Calendar now1 = Calendar.getInstance(); Calendar now2 = new GregorianCalendar(); Calendar now3 = new GregorianCalendar(2016, 01, 24); Calendar now4 = new GregorianCalendar(2016, 01, 24, 15, 55); //Trail: Calendar's month is 0~11 Calendar now5 = new GregorianCalendar(2016, 01, 24, 15, 55, 44); Calendar now6 = new GregorianCalendar(Locale.US); Calendar now7 = new GregorianCalendar(TimeZone.getTimeZone("GMT-8:00")); //Set Calendar now2.setTime(new Date()); System.out.println(now2); now2.setTimeInMillis(new Date().getTime()); System.out.println(now2); //Define the Chinese output format of the date and output the date SimpleDateFormat df = new SimpleDateFormat("yyyyy year MM month dd day hh hour mm minute ss seconds E", Locale.CHINA); System.out.println("Get the Chinese formatted output of the date: " + df.format(now5.getTime())); System.out.println(); System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- System; System.out.println("Get year: " + now5.get(Calendar.YEAR)); System.out.println("Get month (month starts from 0): " + now5.get(Calendar.MONTH)); System.out.println("Get day: " + now5.get(Calendar.DAY_OF_MONTH)); System.out.println("Get day: " + now5.get(Calendar.HOUR)); System.out.println("Get points: " + now5.get(Calendar.MINUTE)); System.out.println("Get seconds: " + now5.get(Calendar.SECOND)); System.out.println("Get morning and afternoon: " + now5.get(Calendar.AM_PM)); System.out.println("Get the week value (week starts from Sunday): " + now5.get(Calendar.DAY_OF_WEEK)); System.out.println(); System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; System.out.println("now5 object's month is: " + months[now5.get(Calendar.MONTH)]); } public void testCalendar2() throws ParseException{ //Get the maximum number of days in the current month Calendar cal = Calendar.getInstance(); int maxday=cal.getActualMaximum(Calendar.DAY_OF_MONTH); int mindday=cal.getActualMinimum(Calendar.DAY_OF_MONTH); System.out.println(maxday); //Take the last day of the month DateFormat formatter3=new SimpleDateFormat("yyyy-MM-"+maxday); System.out.println(format3.format(cal.getTime())); //Take the last day of the month DateFormat formatter4=new SimpleDateFormat("yyyy-MM-"+minday); System.out.println(formatter4.format(cal.getTime())); //Find the number of days between two dates java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd"); java.util.Date beginDate= format.parse("2007-12-24"); java.util.Date endDate= format.parse("2007-12-25"); long day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000); System.out.println("Number of days apart="+day); //Date one year ago java.text.Format formatter5=new java.text.SimpleDateFormat("yyyy-MM-dd"); java.util.Date todayDate=new java.util.Date(); long beforeTime=(todayDate.getTime()/1000)-60*60*24*365; todayDate.setTime(beforeTime*1000); String beforeDate=formatter5.format(todayDate); System.out.println(beforeDate); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, -1); System.out.println(formatter5.format(calendar.getTime())); //The Monday and Sunday of the current week SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); GregorianCalendar gregorianCalendar = new GregorianCalendar(); int dayInWeek = gregorianCalendar.get(Calendar.DAY_OF_WEEK); int offset = 0; if (dayInWeek == 1) { // Sunday offset = 6; } else { // Monday to Saturday offset = dayInWeek - 2; } gregorianCalendar.add(GregorianCalendar.DAY_OF_MONTH, -offset); String sday = dateFormat.format(gregorianCalendar.getTime()); gregorianCalendar.add(GregorianCalendar.DAY_OF_MONTH, 6); String eday = dateFormat.format(gregorianCalendar.getTime()); System.out.println("Monday of this week:" + sday); System.out.println("Sunday of this week:" + eday); } }3. Summary
There are often five aspects of dates in Java:
1. Creation date
2. Date format display
3. Date conversion (mainly mutual conversion with strings)
4. Obtain the dates of middle age, month, day, hour, minute, second, week, month, etc.
5. Comparison of date size and addition and subtraction of dates.
The above is the Java date and time usage method summarized for you. I hope it will be helpful to your learning.