首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据时区和DST的纯时间输入和帐户更改日期?

如何根据时区和DST的纯时间输入和帐户更改日期?
EN

Stack Overflow用户
提问于 2015-06-03 10:44:08
回答 1查看 230关注 0票数 0

我需要根据用户提供的两个字符串创建一个新的Date:日期(例如"1.1.2015")和一天中的时间(例如"23:00")。首先,用户输入日期,该日期被发送到服务器并被解析为Date (一天中的时间设置为用户时区中的午夜)。在此之后,用户输入发送到服务器的一天中的时间,需要创建一个新的Date,将来自第一个Date实例的日期和来自新用户输入的一天中的时间结合起来。

例如:假设服务器的时区为UTC,用户的时区为UTC-2。用户将" 1.1.2015“输入日期字段,该字段在服务器中解释为2:00 1.1.2015 UTC (1月1日凌晨2:00在UTC,即用户时区的午夜)。然后,用户将"23:00“输入时间字段(24小时时钟)。这需要在服务器中解释为1:00 2.1.2015 UTC (1月2日凌晨1:00 )。

我们使用Apache将字符串转换为FastDateFormat,反之亦然,使用Joda时间进行数据操作。结果需要是一个简单的旧Java日期。我尝试将现有的Date实例和用户每天输入的时间组合在一起,如下所示:

代码语言:javascript
复制
Date datePart= ...; // The date parsed from the first user input
FastDateFormat timeFormat = ...;
DateTimeZone userTimeZone = DateTimeZone.forTimeZone(timeFormat.getTimeZone());
String userTimeInput = ...; // The time of day from the user

MutableDateTime dateTime = new MutableDateTime(datePart, DateTimeZone.UTC);
Date newTime = timeFormat.parse(userTimeInput);
dateTime.setTime(new DateTime(newTime, DateTimeZone.UTC));

// Determine if the date part needs to be changed due to time zone adjustment
long timeZoneOffset = userTimeZone.getOffset(dateTime);
long newMillisOfDay = dateTime.getMillisOfDay();
if (newMillisOfDay + timeZoneOffset > 24 * 60 * 60 * 1000) {
    dateTime.addDays(-1);
} else if (newMillisOfDay + timeZoneOffset < 0) {
    dateTime.addDays(1);
}

Date newServerDate = dateTime.toDate();

像这样改变现有Date的时间有点问题。上述操作不起作用;如果用户多次更改一天中的时间,则每次都可能进行+/-1天调整。另外,上面的代码没有考虑到DST。如果datePart在DST中,则我们的示例用户输入的时间应该被视为位于UTC-1中。当使用FastDateFormat并仅解析一天中的时间时,日期被设置为一个时代,这意味着用户输入的时间将始终被视为位于UTC-2中。这将导致结果中一个小时的偏移。

如何根据一天中给定的时间调整服务器中的Date,并适当考虑时区和DST?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-09 05:29:40

我在评论中使用了Jon的建议来解决这个问题。我仍然需要一个Date,所以我不能开始使用Joda的时间来处理所有的事情。但是,对于这个特定的用例,我确实离开了FastDateFormat和MutableDateTime。谢谢你的小费!解决方案如下:

代码语言:javascript
复制
Date datePart= ...;           // The date parsed from the first user input
String userTimeInput = ...;   // The time of day from the user
Locale userLocale = ...;
DateTimeZone userTimeZone = ...;

DateTime dateInUserTimeZone = new DateTime(datePart, userTimeZone);
DateTimeFormatter formatter = DateTimeFormat.shortTime().withLocale(userLocale);
LocalTime time = formatter.parseLocalTime(userTimeInput);

Date newDate = dateInUserTimeZone.withTime(time.getHourOfDay(), time.getMinuteOfHour(),
        time.getSecondOfMinute(), time.getMillisOfSecond()).toDate();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30617832

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档