4

Time flies so fast, it's already 2022. As development, time processing is very cumbersome. From Java 8 began new time API , processing time more elegant, no longer need the help of the tripartite library, and thread-safe. Today, let's sort out the formatting of the new API, and play something you haven't played before, like, retweet, and watch it again.

Time formatting for the new API

Time formatting for the new time API is java.time.format.DateTimeFormatter

localized time

Combined with the styles defined by FormatStyle DateTimeFormatter predefines time formats based on the local ( Locale ) style. Let's look at this code:

        String format = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
                .format(ZonedDateTime.now());

If you are in China, format the result:

2022年1月6日 下午4:22:01

If you are in the US:

Jan 6, 2022, 4:21:10 PM

There are three static methods and their overloads to format the localization time, which have been organized into a mind map:

本地化时间

ISO/RFC canonical format

DateTimeFormatter also has built- ISO and RFC , based on the built-in static instance DateTimeFormatter 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 shown in the following table:

内置ISO、RFC规范格式

Paradigm formatting

This method should be the most commonly used method. from letters and symbols ( 161d80f3342331 Patterns ), use the ofPattern(String) or ofPattern(String, Locale) method to pass the constructed pattern. For example, d MMM uuuu will format 2011-12-03 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.

I believe yyyy-MM-dd HH:mm:ss will show you something you haven't seen before:

        // 最后面是两个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 = 公元 2022年1月7日 +08:00 Asia/Shanghai

The form has been sorted out for you, try it out:

格式化符号对照表

: Felordcn for more information

Personal blog: https://felord.cn


码农小胖哥
3.8k 声望8k 粉丝