0

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

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

我们使用 Apache CommonsFastDateFormat将字符串转换为Dates反之亦然,并使用 Joda Time 进行日期操作。结果需要是一个普通的旧 Java 日期。我尝试将现有Date实例和用户输入的时间结合起来,如下所示:

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 天的调整。另外,上面的代码没有考虑夏令时。如果datePart是 DST,我们的示例用户输入的时间应该被视为 UTC-1。当使用FastDateFormat并仅解析一天中的时间时,日期设置为纪元,这意味着用户输入的时间将始终被视为采用 UTC-2 格式。这将导致结果偏移一小时。

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

4

1 回答 1

0

我通过在评论中使用 Jon 的建议解决了这个问题。我仍然必须以 . 结尾Date,所以我不能开始使用 Joda Time 来处理所有事情。然而,对于这个特定的用例,我确实远离了 FastDateFormat 和 MutableDateTime。感谢您的提示!解决方案如下所示:

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();
于 2015-06-09T05:29:40.107 回答