We may want to output the time according to a certain habit, such as the order of time: year, month, Sunday or year, month, Sunday, hours, minutes and seconds.
In the early days of Java, SimpleDateFormat , a subclass of DateFormat in the java.text package, was used to format dates. JDK 1.5 version provides a more convenient Formatter class . The format method of the Formatter class is as follows:
format (format mode, date list)
According to the "Format Mode", return the string representation of the data (year, month, day, hour, etc.) contained in each date listed in the "Date List".
Currently, Java has made the format method a static method of the String class. Therefore, the program can directly use the String class to call the format method to format the date.
The "format mode" in the format method is a character sequence enclosed in double quotes, that is, a string. The characters in this character sequence are composed of time format characters and ordinary characters.
For example: %ty, %tm and %td in date: %ty-%tm-%td are all time format characters. The first two Chinese characters ("day" and "period"), colon and format characters are between The connecting characters "-" are all ordinary characters. In layman's terms, anything that is not a time format character is considered an ordinary character.
For example: the format characters %ty, %tm and %td will respectively represent the "year", "month" and "day" in the date.
The string returned by the format method is the string after the time format character in the "formatting mode" is replaced by the formatted result it obtains, for example:
Strings=String.format(%tY year %tm month %td day, newDate(), newDate(), newDate());
The "date list" in the format method can be a comma-separated Calendar object or a Date object .
We need to ensure that the number of format characters in the "format mode" of the format method is the same as the number of dates listed in the "date list".
By default, the format method uses the format characters in the "formatting mode" in order from left to right to format the corresponding dates in the "date list", while the ordinary characters in the "formatting mode" remain unchanged.
If we want to use several format symbols to format the same date in the "Date List", we can use "<" in the "Format Mode", for example: The three format symbols in %ty-%<tm-%<td will Format the same date, that is, the format character containing "<" formats the same date as the format character before it, for example:
Strings=String.format(%tyyear%<tmmonth%<tdday,newDate());
Commonly used date format characters: