Java 查找对应于纽约午夜的UTC日期
我有一个用户将他的时区配置为Java 查找对应于纽约午夜的UTC日期,java,datetime,timezone,jodatime,utc,Java,Datetime,Timezone,Jodatime,Utc,我有一个用户将他的时区配置为美国/纽约。我必须为他安排一个活动,从他午夜开始,到24小时后(下一个午夜)结束。但我想将日期存储在UTC中的数据库中 所以我使用Joda DateTime编写了以下代码片段 DateTime dateTime = new DateTime(DateTimeZone.forID(user.getTimezone())); DateTime todayMidnight = dateTime.toDateMidnight().toDateTime(); // now se
美国/纽约
。我必须为他安排一个活动,从他午夜开始,到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,因此我预计开始日期为2013年2月4日5:0:0
,但对我来说,开始日期为2013年2月3日23:0:0
上面的代码有什么错误吗?我建议您避免完全使用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及其用法。我将在此处尝试并更新上述代码。