首页 > 解决方案 > 将日期(谷歌日历 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

解决方案


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]

ONLINE DEMO

如果我需要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 desugaringHow to use ThreeTenABP in Android Project


推荐阅读