2015-10-18 34 views
6

今天,我們的巴西用戶正在爲我們生成大量的崩潰報告。我跟蹤它到這段代碼,它拋出一個異常喬達:如何防止喬達時間在巴西DST過渡期間拋出異常

import org.joda.time.DateTime; 
import org.joda.time.DateTimeUtils; 
import org.joda.time.DateTimeZone; 
import org.joda.time.LocalTime; 

public class ScratchSpace { 

    public static void main(String[] args) { 
     // force Joda to act like we are in Sao Paolo on 2015-10-18 
     DateTimeUtils.setCurrentMillisFixed(1445185758078L); // 2015-10-18T18:29 
     DateTimeZone.setDefault(DateTimeZone.forID("America/Sao_Paulo")); 

     // most of users have offset == 0, but it could be any number of millis from 0 to 86_400_000-1 (millis in day) 
     int offset = 0; 

     // local time at start of day + offset millis 
     final LocalTime localTime = LocalTime.fromMillisOfDay(offset); 

     // convert to a time on the current day 
     DateTime dateTime = localTime.toDateTimeToday(); // throws org.joda.time.IllegalFieldValueException exception 
     System.out.println("dateTime = " + dateTime); 
    } 
} 

例外:

Exception in thread "main" org.joda.time.IllegalFieldValueException: Value 0 for hourOfDay is not supported: Illegal instant due to time zone offset transition (daylight savings time 'gap'): 2015-10-18T00:29:18.078 (America/Sao_Paulo) 
    at org.joda.time.chrono.ZonedChronology$ZonedDateTimeField.set(ZonedChronology.java:486) 
    at org.joda.time.chrono.BaseChronology.set(BaseChronology.java:240) 
    at org.joda.time.LocalTime.toDateTimeToday(LocalTime.java:1287) 
    at org.joda.time.LocalTime.toDateTimeToday(LocalTime.java:1270) 

我使用Java 1.8.0_60在OS X 10.11與喬達時間2.8。 2。

什麼解決方法將允許我正確地獲取DateTime實例,表示當天的時間爲,偏移量爲毫秒,一天開始後的毫秒數?

回答

3

不要走LocalTime。創建日期時間,並添加以毫秒爲單位的偏移量:

DateTime startOfDay = LocalDate.now().toDateTimeAtStartOfDay(); 
DateTime dateTime = startOfDay.plus(offset); 

System.out.println("dateTime = " + dateTime); 
相關問題