Home >Java >javaTutorial >How to implement Java API time formatting
The time formatting of the new time API is handled by java.time.format.DateTimeFormatter
.
Combined with the style defined by the enumeration FormatStyle
, DateTimeFormatter
is predefined based on local (Locale
) Style time format.
Let’s take a look at this code:
String format = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).format(ZonedDateTime.now());
If you are in China, format the result:
January 6, 2022 4:22:01 pm
If you are in the United States:
Jan 6, 2022, 4:21: 10 PM
There are three static methods and their overloads to format localization time. The details have been compiled into a mind map:
DateTimeFormatter
also has built-in time formats of ISO and RFC, based on the built-inDateTimeFormatter
Static instance.
For example:
// 静态实例 DateTimeFormatter isoWeekDateFormatter = DateTimeFormatter.ISO_WEEK_DATE; // 执行格式化 String format = isoWeekDateFormatter.format(LocalDateTime.now()); // format = 2022-W01-4 System.out.println("format = " + format);
Others are as shown in the following table:
This method should be our most commonly used method. To construct a pattern (Patterns) through letters and symbols, use the ofPattern(String)
or ofPattern(String, Locale)
method to pass the constructed pattern. 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, is immutable, and is thread-safe.
What to believeyyyy-MM-dd HH:mm:ss
You are tired of playing, let me show you something you have never seen:
// 最后面是两个V 不是W 单个V会报错 String pattern = "G uuuu'年'MMMd'日' ZZZZZ VV"; String format= DateTimeFormatter.ofPattern(pattern).format(ZonedDateTime.now()); // format = 2022-W01-4 System.out.println("format = " + format);
Output:
format = January 7, 2022 08:00 Asia/Shanghai
The form has been sorted out for you, you can try it Give it a try:
At this point, I believe that everyone has a deeper understanding of "How to implement Java's API time formatting", so you might as well do it in practice. ! This is this site. For more related content, you can enter the relevant channels for inquiry. Follow us and continue learning!
The above is the detailed content of How to implement Java API time formatting. For more information, please follow other related articles on the PHP Chinese website!