栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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用得比较多,记录一下,下次就不用百度了

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/572450.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号