How time flies, it’s already 2022. As a development, time handling is cumbersome. Starting with Java 8, there is a new time API, time handling is more elegant, no longer requires the use of third-party libraries, and thread safety. Today we’re going to go through the formatting of the new API, and we’re going to play some stuff you haven’t played before, like it, retweet it, and watch it.
New API time formatting
The time of the new API format by Java. Time. Format. DateTimeFormatter is responsible for.
Localization time
Combined with the styles defined by the enumerated FormatStyle, the DateTimeFormatter predefined time formats based on the Locale style. Let’s look at this code:
String format = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
.format(ZonedDateTime.now());
Copy the code
If you are in China, format the result:
January 6, 2022 4:22:01 PMCopy the code
If you are in the United States:
Jan 6, 2022, 4:21:10 PM
Copy the code
There are three static methods with overloads to format localization time, which have been organized into mind maps:
ISO/RFC standard format
The DateTimeFormatter also comes with built-in ISO and RFC time formats, based on built-in static instances of the DateTimeFormatter. Here’s an example:
// Static instance
DateTimeFormatter isoWeekDateFormatter = DateTimeFormatter.ISO_WEEK_DATE;
// Perform formatting
String format = isoWeekDateFormatter.format(LocalDateTime.now());
// format = 2022-W01-4
System.out.println("format = " + format);
Copy the code
Others are shown in the following table:
Normal form formatting
This is probably the way we use it the most. Patterns are constructed using letters and symbols, and the constructed Patterns are passed using ofPattern(String) or ofPattern(String, Locale) methods. For example, d MMM uuuu will format 2011-12-03 as December 3, 2011. A format created from a schema can be used as many times as needed, it is immutable, and it is thread-safe.
Believe in yyyY-MM-DD HH: MM: SS you’re sick of it, fat boy show you something you’ve never seen before:
// The last two V's are not W's
String pattern = "G uuuu' year 'MMMd' day 'ZZZZZ VV";
String format= DateTimeFormatter.ofPattern(pattern).format(ZonedDateTime.now());
// format = 2022-W01-4
System.out.println("format = " + format);
Copy the code
Output:
Format = 7 January 2022 AD +08:00 Asia/ShanghaiCopy the code
The form is ready for you. Try it:
Follow our public id: Felordcn for more information
Personal blog: https://felord.cn