【问题标题】:Convert a specific time in one timezone to another timezone [duplicate]将一个时区中的特定时间转换为另一个时区[重复]
【发布时间】:2021-11-16 11:01:48
【问题描述】:

我正在尝试将美国东部标准时间上午 8:00(美国/纽约)转换为显示在用户系统默认区域上的任何时间。不需要日期,只需要时间。我一直在寻找,我只能找到转换当前时间的方法。

【问题讨论】:

  • 快速 google 搜索以 Convert date and time between timezone 开头。然后显示由DateTimeFormatter 处理,但由于您可以拥有超过 +/- 12 小时的时区,因此日期很重要
  • 您好,请注意,在此处发布问题之前,您需要先进行搜索。在许多情况下,这会给你一个更好的答案,比任何人都可以在这里输入一个简短的答案更快。如果您的搜索还不够,请告诉我们您发现了什么以及它如何未能解决您的问题。表现出你的努力将使许多用户准备好为他们的努力做出更大的努力。他们会更准确地知道你需要知道什么,提供对你更有帮助的答案。
  • America/New_York 在一年中的大部分时间都处于夏季时间(DST、EDT)。转换必须根据是否在当天不同,还取决于用户的默认时区是否是。那么我们能知道日期吗?否则,您将无法执行转换。

标签: java timezone java-time zoneddatetime


【解决方案1】:

您需要使用ZonedDateTime 并使用DateTimeFormatter 仅显示时间部分。像这样的:

//assuming the server is in US
        ZoneId serverZone = ZoneId.of("US/Eastern");
        ZoneId userZone = ZoneId.of("Asia/Tokyo");
        
        ZonedDateTime nyTime = ZonedDateTime.now(serverZone);
        ZonedDateTime userTime = nyTime.withZoneSameInstant(userZone);
        
        String pattern = "hh:mm a z VV";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
        
        System.out.println("Server time: " + dtf.format(nyTime));
        System.out.println("User time:   " + dtf.format(userTime));
        

输出:

Server time: 08:29 AM EDT US/Eastern
User time:   09:29 PM JST Asia/Tokyo

【讨论】:

  • 这不会给你当前时间:ZonedDateTime.of(LocalDateTime.now(), serverZone)。使用ZoneDateTime.now(serverZone)
【解决方案2】:

出于示例的目的,我假设您希望将今天上午 8 点 EDT 转换为用户的默认时区。如果没有日期,我们将无法正确执行转换。就像其他答案中的 onkar ruikar 一样,我正在使用并推荐现代 Java 日期和时间 API java.time,用于您所有的时间工作。

    ZoneId sourceZone = ZoneId.of("America/New_York");
    ZoneId targetZone = ZoneId.systemDefault();
    
    LocalTime sourceTime = LocalTime.of(8, 0);
    
    ZonedDateTime sourceDateTime = ZonedDateTime.now(sourceZone).with(sourceTime);
    ZonedDateTime targetDateTime = sourceDateTime.withZoneSameInstant(targetZone);
    LocalTime targetTime = targetDateTime.toLocalTime();
    
    System.out.println(targetTime);

我今天在 America/Sao_Paulo 时区跑步时的输出:

09:00

在每年的这个时候(9 月),北美东部时间在包括纽约在内的大多数地方的 UTC 偏移量为 -04:00,而圣保罗在 -03:00,因此时间增加了 1 小时.

如果我在 12 月运行代码,输出将是:

11:00

到那时,由于夏季时间,纽约的偏移量为 -05:00,圣保罗的偏移量为 -02:00,因此需要增加 3 小时。

链接

Oracle tutorial: Date Time 解释如何使用 java.time。

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 2012-10-27
    • 2012-01-30
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多