string类和LocalDateTime的相互转换方式

您所在的位置:网站首页 字符串转localdate string类和LocalDateTime的相互转换方式

string类和LocalDateTime的相互转换方式

#string类和LocalDateTime的相互转换方式| 来源: 网络整理| 查看: 265

目录string类和LocalDateTime相互转换1.Locahttp://www.cppcns.comlDateTIme转换2.LocalDate转换string转化LocalDateTime类出现的问题

string类和LocalDateTime相互转换

String类和LocalDateTime类的相互转换,这种类型之间的相互转换

记住三点就行:

1.具有转换功能的对象2.要转换的对象3.用具有转换功能的对象发动功能----操作-----要转换的对象

1. LocalDateTIme转换 //1.具有转换功能的对象 DateTimeFormatter df = Datwww.cppcns.comeTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); //2.要转换的对象 LocalDateTime time = LocalDateTime.now编程客栈(); //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类型的时间转成LocalDateTwww.cppcns.comime:"+LocalTime);

2.LocalDate转换 DateTimeFormatter struct = DateTimeFormatter.ofPattern("yyyy-MM-dd") LocalDate localDate = LocalDate.now(); 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:48String类型的时间转成LocalDateTime:2020-11-09T18:32:48LocalDate转成String类型的时间: 2020-11-09String类型的时间转成LocalDateTime:2020-11-09

string转化LocalDateTime类出现的问题 LocalDateTime now = LocalDateTime.now(); final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd w hh:mm:ss"); 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&rdquybmvFiuHFo;

tips:年用YYYY格式也会出现异常

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

string类和LocalDateTime的相互转换方式


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3