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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值