2021-11-19 ZonedDateTime与字符串互转

因为经常要使用ZonedDateTime,涉及到与字符串的相互转换
一、ZonedDateTime转为字符串

ZonedDateTime now = ZonedDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”);
String time = now.format(formatter);
log.info(time);

执行结果

2021-11-19 14:09:08

二、字符串转为ZonedDateTime

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”).withZone(ZoneId.of(“Asia/Shanghai”));
ZonedDateTime time = ZonedDateTime.parse(“2021-11-19 14:09:30”, formatter);
log.info(“转换后:” + time);

执行结果

转换后:2021-11-19T14:09:30+08:00[Asia/Shanghai]

网上查阅说withZone方法一定要,不然会报错

Unable to obtain ZoneId from TemporalAccessor: {},ISO resolved to 2021-11-19T14:09:30 of type java.time.format.Parsed

这次的使用场景为:前端传入字符串的时间,我需要通过这个时间区间查询数据库,所以需要把字符串转为ZonedDateTime。发现ZonedDateTime用得比较多,记录一下,下次就不用百度
————————————————
版权声明:本文为CSDN博主「神奇的凹凸曼」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44092667/article/details/121421374

Original: https://www.cnblogs.com/telwanggs/p/16541231.html
Author: 疯子110
Title: 2021-11-19 ZonedDateTime与字符串互转

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/545518/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球