如何防止Joda Time在巴西DST过渡期间抛出异常

时间:2015-10-18 16:47:16

标签: java jodatime

今天,我们的巴西用户正在为我们制作大量的崩溃报告。我已将其跟踪到此代码,该代码抛出了Joda异常:

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)

我在OS X 10.11上使用Java 1.8.0_60和Joda Time 2.8.2。

什么样的解决方法可以让我正确地获得一个DateTime实例,该实例表示当天开始时偏移毫秒的当天时间?

1 个答案:

答案 0 :(得分:3)

不要去当地时间。创建一个DateTime,并以毫秒为单位添加偏移量:

eat()