【问题标题】:how to get and format date with timezone如何使用时区获取和格式化日期
【发布时间】:2019-11-18 21:58:49
【问题描述】:

我正在创建一个日期并将其存储到数据库中,我想获取当前时间,即 timezone = "Asia/Istanbul" 而不是我的当地时间。

我正在本地计算机中创建日期,我的本地时区也是“亚洲/伊斯坦布尔”。

当我将它部署到我的服务器时,服务器时区是 utc,它每次都转向 utc。

我有不同的 2 台机器,2 台机器有不同的时区,所以我需要用时区设置我的数据日期。

这就是我所做的。在我的本地计算机上没问题,但在 UTC 的服务器上失败

LocalDateTime localDateTime = LocalDateTime.now();
// it gives my local date time, 2019-07-09T10:30:03.171
// local date is now 1:30 pm, UTC is 3 hours after, it looks ok.
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Asia/Istanbul"));
//2019-07-09T10:30:03.171+03:00[Asia/Istanbul]
// it looks +3. I dont want to see +3, I want the date like 01:30 which is shiefted
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
zonedDateTime.format(formatter);
//2019-07-09T07:30:03.171Z
// zone is disappeared, this is 3 hours before UTC

我希望创建它时像亚洲/伊斯坦布尔这样的日期。

【问题讨论】:

  • 错误的类。 LocalDateTime 故意缺少任何时区或与 UTC 偏移的概念。阅读class Javadoc。该类不能代表时刻,即时间线上的特定点。我想不出任何情况下调用LocalDateTime.now() 是正确的做法。

标签: java date timezone localdate


【解决方案1】:

我根本不会使用LocalDateTime。始终使用ZonedDateTime 以消除对时间的任何疑问。还要始终将ZoneId(如果不是Clock)传递给now 方法。这使您的代码独立于计算机和 JVM 的时区设置。

    ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Asia/Istanbul"));
    System.out.println(zonedDateTime);

2019-07-09T14:14:17.280852+03:00[亚洲/伊斯坦布尔]

您可能误解了+03:00 部分,人们有时会这样做。这意味着显示的时间已经比 UTC 早 3 小时。所以显示的时间点等于 11:14:17 UTC。

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    System.out.println(zonedDateTime.format(formatter));

2019-07-09 14:14:17

您的格式化程序不包含时区,因此未显示。但现在是伊斯坦布尔的时间。

你的代码出了什么问题?

我假设您代码中的 cmets 是在您的服务器上以 UTC 运行的(不是很清楚),并且您在 UTC 时间 10:30 左右运行代码,与伊斯坦布尔的 13:30 相同。

LocalDateTime 是没有时区和 UTC 偏移的日期和时间。它的无参数 now 方法使用 JVM 的时区设置,在本例中为 UTC,因此在相关日期为您提供 10:30。我认为ZonedDateTime.of 在这里是错误的:它从LocalDateTime 和伊斯坦布尔时区获取 ZoneId 对象的 10:30,并在伊斯坦布尔为您提供 10:30,这不是您想要的。你想要的是 13:30,也就是下午 1:30。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多