java - 将日期(谷歌日历 api)转换为带时区的日期
问题描述
我正在尝试将 a 转换localdatetime
为日期(我在 Google Calendar api 方法中使用)
Zone Id = "America/New_York"
我总是得到这个结果:
2021-08-10T00:00:00.000+02:00
+02:00 是我的本地时区
我想获得-04:00 America/New_York
与上述相同的格式
这是方法
public static Date toDate(LocalDateTime startTime, String zoneId) {
ZoneId zonedId = ZoneId.of(zoneId);
return Date.from(Instant.from(startTime.atZone(zonedId)));
}
请问有人可以帮忙吗?
解决方案
java.time
java.util
日期时间 API 及其格式化 API已SimpleDateFormat
过时且容易出错。建议完全停止使用它们并切换到现代 Date-Time API *。
使用java.time
现代日期时间 API 的示例解决方案:您可以ZonedDateTime#withZoneSameInstant
用于此目的。
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZoneId sourceZone = ZoneId.of("Europe/Berlin");
ZonedDateTime zdtSource = ZonedDateTime.now(sourceZone);
System.out.println(zdtSource);
ZoneId targetZone = ZoneId.of("America/New_York");
ZonedDateTime zdtTarget = zdtSource.withZoneSameInstant(targetZone);
System.out.println(zdtTarget);
}
}
示例运行的输出:
2021-08-10T20:06:24.023038+02:00[Europe/Berlin]
2021-08-10T14:06:24.023038-04:00[America/New_York]
如果我需要OffsetDateTime
怎么办?
你可以ZonedDateTime#toOffsetDateTime
用来OffsetDateTime
摆脱一个ZonedDateTime
物体,例如
OffsetDateTime odtTarget = zdtTarget.toOffsetDateTime();
注意:无论出于何种原因,如果您需要将此对象转换ZonedDateTime
为 的对象java.util.Date
,您可以执行以下操作:
Date date = Date.from(zdtTarget.toInstant());
从Trail: Date Time了解有关现代日期时间 API *的更多信息。
* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,则可以使用ThreeTen-Backport,它将大部分java.time功能向后移植到 Java 6 和 7。如果您正在为 Android 项目和 Android API 工作level 仍然不符合 Java-8,请检查Java 8+ APIs available through desugaring和How to use ThreeTenABP in Android Project。
推荐阅读
- visual-studio - 闪烁的文字和改变颜色
- java - 如何获取文档内数组的索引
- python - 如何在 Python 中模拟继承的协作方法
- jpa - 如何使用 RapidClipse 生成交叉表?
- linux - 如何确保由 docker 容器创建的文件不属于 root
- css - 父级的背景不过渡(幻灯片)
- scala - 未找到请求操作的编解码器:[varchar <-> java.lang.Double],从 spark 结构插入 Datastax cassandra
- xamarin - (Xamarin) 将数据从 XAML 传递到 XAML.cs
- python - 删除中文字符
- javascript - 根据用户是否登录,在 React 中更改 Navbar 值的正确方法是什么?