0

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

所以我使用 Joda DateTime 编写了以下代码段。

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

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

4

1 回答 1

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());
于 2013-02-04T07:07:17.970 回答