package com.test.test02; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.time.temporal.TemporalAccessor; public class Test10 { //这是一个main方法,是程序的入口 public static void main(String[] args) { //格式化类:DateTimeFormatter //方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME; ISO_LOCAL_DATE ISO_LOCAL_TIME DateTimeFormatter df1 = DateTimeFormatter.ISO_LOCAL_DATE_TIME; //df1就可以帮助我们完成LocalDateTime和String之间的相互转换 //LocalDateTime--->String LocalDateTime now = LocalDateTime.now(); String str = df1.format(now); System.out.println(str); //2023-05-09T14:22:07.687 //String--->LocalDateTime TemporalAccessor parse = df1.parse("2023-05-09T14:22:07.687"); System.out.println(parse);//{},ISO resolved to 2023-05-09T14:22:07.687 //方式二:本地化相关的格式。如:oflocalizedDateTime() //参数:FormatStyle.LONG/FormatStyle.MEDIUM/FormatStyle.SHORT //FormatStyle.LONG:2023年5月9日 下午02时35分39秒 LONG是这样的格式 //FormatStyle.MEDIUM:2023-5-9 14:37:05 MEDIUM是这样的格式 //FormatStyle.SHORT:23-5-9 下午2:37 SHORT是这样的格式 DateTimeFormatter df2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT); //LocalDateTime--->String LocalDateTime now1 = LocalDateTime.now(); String str1 = df2.format(now1); System.out.println(str1); //2023年5月9日 下午02时35分39秒 2023-5-9 14:37:05 23-5-9 下午2:37 //String--->LocalDateTime 类型需要对应,下面的不是short类型运行就不对了 TemporalAccessor parse1 = df2.parse("23-5-9 下午2:37"); System.out.println(parse1); //{},ISO resolved to 2023-05-09T14:37 //方式三:自定义的格式。如:ofPattern("yyyy-MM-dd hh:mm:ss") --->重点,以后常用 DateTimeFormatter df3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); //LocalDateTime--->String LocalDateTime now2 = LocalDateTime.now(); String str2 = df3.format(now2); System.out.println(str2); //2023-05-09 02:48:56 //String--->LocalDateTime TemporalAccessor parse2 = df3.parse("2023-05-09 02:48:56"); System.out.println(parse2); //{HourOfAmPm=2, MinuteOfHour=48, MilliOfSecond=0, NanoOfSecond=0, SecondOfMinute=56, MicroOfSecond=0},ISO resolved to 2023-05-09 } }
java格式化类DateTimeFormatter的使用
最新推荐文章于 2023-06-10 11:53:51 发布