java - 指定 ZonedDateTime 的时区而不更改实际日期
问题描述
我有一个包含日期(不是当前日期)的 Date 对象,我需要以某种方式指定该日期为 UTC,然后将其转换为 +1 小时的“欧洲/巴黎”。
public static LocalDateTime toLocalDateTime(Date date){
return ZonedDateTime.of(LocalDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC), ZoneId.of("Europe/Paris")).toLocalDateTime();
}
给定日期“2018-11-08 15:00:00”,这会将日期转换为“2018-11-08 14:00:00”。我需要它从 UTC 转换为欧洲/巴黎 - 而不是相反。
解决方案
您可以使用ZonedDateTime.withZoneSameInstant()
方法从 UTC 移动到巴黎时间:
Date date = new Date();
ZonedDateTime utc = date.toInstant().atZone(ZoneOffset.UTC);
ZonedDateTime paris = utc.withZoneSameInstant(ZoneId.of("Europe/Paris"));
System.out.println(utc);
System.out.println(paris);
System.out.println(paris.toLocalDateTime());
打印:
2018-11-08T10:25:18.223Z
2018-11-08T11:25:18.223+01:00[Europe/Paris]
2018-11-08T11:25:18.223
推荐阅读
- python - Boto3:TypeError:列表索引必须是整数或切片,而不是 str
- oracle-apex - 图片上传没有页面刷新和提交按钮
- mobx - Mobx 只观察数组中的特定对象
- php - Laravel 验证不适用于多字节字符
- sql - 具有 2 个值和一个日期列的 PIVOT 查询
- react-native - 存储在 s3 Bucket 上的图像未加载到物理设备上 - React Native
- sql - 从 Oracle 中均匀分布的值列表生成随机值
- html - 跨浏览器保持表情符号一致
- javascript - 如何在 asp.net 中使用 XMLHttpRequest 从带有 Post 方法的页面获取响应文本?
- sql - mssql cdc update_mask 过滤器更改仅在列 TS