string类和LocalDateTime的相互转换⽅式
⽬录
string类和LocalDateTime相互转换
1.LocalDateTIme转换
2.LocalDate转换
string转化LocalDateTime类出现的问题
string类和LocalDateTime相互转换
String类和LocalDateTime类的相互转换,这种类型之间的相互转换
记住三点就⾏:
1.具有转换功能的对象
2.要转换的对象
3.⽤具有转换功能的对象发动功能----操作-----要转换的对象
1. LocalDateTIme转换
//1.具有转换功能的对象
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//2.要转换的对象
LocalDateTime time = w();
//3.发动功能
String localTime = df.format(time);
System.out.println("LocalDateTime转成String类型的时间:"+localTime);
//3.LocalDate发动,将字符串转换成 df格式的LocalDateTime对象,的功能
LocalDateTime LocalTime = LocalDateTime.parse(strLocalTime,df)
System.out.println("String类型的时间转成LocalDateTime:"+LocalTime);
2.LocalDate转换
DateTimeFormatter struct = DateTimeFormatter.ofPattern("yyyy-MM-dd")
LocalDate localDate = w();
String format = struct.format(localDate)
System.out.println("LocalDate转成String类型的时间:"+format)
LocalDate parse = LocalDate.parse(format
System.out.println("String类型的时间转成LocalDateTime:"+parse);
结果:
LocalDateTime转成String类型的时间:2020-11-09 18:32:48
String类型的时间转成LocalDateTime:2020-11-09T18:32:48
LocalDate转成String类型的时间: 2020-11-09
String类型的时间转成LocalDateTime:2020-11-09
string转化LocalDateTime类出现的问题
LocalDateTime now = w();
final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd w hh:mm:ss");
string转date的方法final String format = now.format(dateTimeFormatter);
System.out.println(format);
final LocalDateTime parse = LocalDateTime.parse(format, dateTimeFormatter);
运⾏会出现
java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {MilliOfSecond=0,
NanoOfSecond=0, HourOfAmPm=9, MicroOfSecond=0, SecondOfMinute=57, MinuteOfHour=34},ISO resolved to 2020-04-13 of type java.time.format.Parsed
原因是因为时间格式中的⼩时 hh 采⽤12⼩时,反解析时不知道上午还是下午,改成 "yyyy-MM-dd w hh:mm:ss a"或者采⽤24⼩时制“yyyy-MM-dd w HH:mm:ss”
tips:年⽤YYYY格式也会出现异常
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论