簡體   English   中英

如何基於僅時間輸入並考慮時區和DST來更改日期?

[英]How to change a Date based on time-only input and account for time zone and DST?

我需要基於用戶提供的兩個字符串創建一個新的Java Date :日期(例如“ 1.1.2015”)和一天中的某個時間(例如“ 23:00”)。 首先,用戶輸入日期,該日期將發送到服務器並解析為Date (在用戶所在的時區中,將Date設置為午夜)。 此后,用戶輸入一天中的時間,該時間將發送到服務器,並需要創建一個新的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 Commons FastDateFormat將字符串轉換為Dates ,反之亦然,並使用Joda Time進行日期操作。 結果必須是一個普通的舊Java Date。 我試圖將現有的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的一天中的Date有點麻煩。 上面的行不通; 如果用戶多次更改一天中的時間,則可能每次都會進行+/- 1天的調整。 另外,上面的代碼沒有考慮DST。 如果datePart在DST中,則應將本示例用戶輸入的時間視為在UTC-1中。 當使用FastDateFormat並僅解析一天中的時間時,日期設置為紀元,這意味着用戶輸入的時間將始終被視為UTC-2。 這將導致結果偏移一小時。

如何根據給定的時間調整服務器中的Date ,並適當考慮時區和夏令時?

我通過在評論中使用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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM