【问题标题】:Finding UTC date corresponding to NewYork midnight查找与纽约午夜对应的 UTC 日期
【发布时间】:2013-01-18 20:34:52
【问题描述】:

我有一个用户将他的时区配置为 America/New_York 。我必须为他安排一个活动,该活动应该在他的午夜开始,并在 24 小时后(下一个午夜)结束。但我想将日期存储在UTC 的数据库中。

所以我使用 Joda DateTime 编写了以下 sn-p。

DateTime dateTime = new DateTime(DateTimeZone.forID(user.getTimezone()));
DateTime todayMidnight = dateTime.toDateMidnight().toDateTime();
// now setting the event start and end time
event.setStartTime(todayMidnight.toDate());
event.setEndTime(todayMidnight.plusDays(1).toDate());

请注意,我的服务器在 UTC 时区运行,

America/New_York 是 UTC-5,所以我希望 startdate 是 4th Feb 2013 5:0:0 但对我来说,它会将开始日期设置为 3rd Feb 2013 23:0:0

上面的代码有什么问题吗?

【问题讨论】:

    标签: java datetime timezone jodatime utc


    【解决方案1】:

    我建议您完全避免使用DateMidnight。 (纽约可能没问题,但在其他时区,由于夏令时更改,有些日子不存在午夜。)使用LocalDate 表示日期。

    例如:

    DateTimeZone zone = DateTimeZone.forID(user.getTimezone());
    // Defaults to the current time. I'm not a fan of this - I'd pass in the
    // relevant instant explicitly...
    DateTime nowInZone = new DateTime(zone);
    LocalDate today = nowInZone.toLocalDate();
    DateTime startOfToday = today.toDateTimeAtStartOfDay(zone);
    DateTime startOfTomorrow = today.plusDays(1).toDateTimeAtStartOfDay(zone);
    
    event.setStartTime(startOfToday.toDate());
    event.setEndTime(startOfTomorrow.toDate());
    

    【讨论】:

    • 谢谢乔恩。我将不得不阅读有关 LocalDate 及其用法的信息。将尝试上面的代码并在此处更新。
    猜你喜欢
    • 2012-10-03
    • 2017-08-24
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    相关资源
    最近更新 更多