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 = 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类型的时间转成LocalDateTime:"+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:48
String类型的时间转成LocalDateTime:2020-11-09T18:32:48
LocalDate转成String类型的时间: 2020-11-09
String类型的时间转成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”
tips:年用YYYY格式也会出现异常
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
通过netty把百度地图API获取的地理位置从Android端发送到Java服务器端的操作方法
这篇文章主要介绍了通过netty把百度地图API获取的地理位置从Android端发送到Java服务器端,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-10-10Springboot+rabbitmq实现延时队列的两种方式
这篇文章主要介绍了Springboot+rabbitmq实现延时队列的两种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-05-05SpringBoot中maven项目打成war包部署在linux服务器上的方法
这篇文章主要介绍了SpringBoot中maven项目打成war包部署在linux服务器上的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-05-05
最新评论