其他分享
首页 > 其他分享> > DateTimeFormatter 格式化或解析日期、时间

DateTimeFormatter 格式化或解析日期、时间

作者:互联网

DateTimeFormatter:格式化或解析日期、时间(类似于simpleDateFormat)

点击查看代码
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //格式化:日期-->字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = formatter.format(localDateTime);
        System.out.println(localDateTime);//2021-09-22T18:18:44.563
        System.out.println(str1);//2021-09-22T18:18:44.563
        //解析:字符串 -->日期
        TemporalAccessor parse = formatter.parse("2021-09-22T18:18:44.563");
        System.out.println(parse);//{},ISO resolved to 2021-09-22T18:18:44.563

点击查看代码
//本地化相关的格式,如ofLocalizedDateTime()
        //FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDateTime
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
        //格式化
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);//21-9-22 下午6:26

        //本地化相关的格式,如ofLocalizedDate()
        //FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        //格式化
        String str3 = formatter2.format(LocalDate.now());
        System.out.println(str3);//2021年9月22日 星期三
点击查看代码
DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //格式化
        String str4 = formatter3.format(LocalDateTime.now());
        System.out.println(str4);//2021-09-22 06:33:08

        //解析
        TemporalAccessor parse1 = formatter3.parse(str4);
        System.out.println(parse1);//{NanoOfSecond=0, MilliOfSecond=0, MinuteOfHour=34, HourOfAmPm=6, SecondOfMinute=6, MicroOfSecond=0},ISO resolved to 2021-09-22

标签:格式化,System,2021,DateTimeFormatter,FormatStyle,println,解析,out
来源: https://www.cnblogs.com/jw-kf/p/15321200.html