Make unit tests with dates pass in all time zones and with/out DST

后端 未结 2 1097
时光取名叫无心
时光取名叫无心 2021-01-14 08:17

How do I make this unit test pass in all time zones independent of whether DST is active or not?

import static org.junit.Assert.*;
import java.text.SimpleDat         


        
相关标签:
2条回答
  • 2021-01-14 08:30

    By default, a new SimpleDateFormat will use the system default time zone. If you want a specific time zone, you should call setTimeZone on it:

    private final static SimpleDateFormat DATE_FORMAT = createFormat();
    
    private static SimpleDateFormat createFormat() {
        // Make sure there are no locale-specific nasties, either...
        SimpleDateFormat ret = new SimpleDateFormat("yyyy.MM.dd'T'HH:mm.ss:SSSZZ",
                                                    Locale.US);
        ret.setTimeZone(TimeZone.getTimeZone("Etc/UTC");
    }
    

    For your second test, you'd want to change it to:

    new DateTime(0L, DateTimeZone.UTC);
    

    Note that you shouldn't usually use a static SimpleDateFormat variable, as it's not thread-safe. (Whereas the Joda Time DateTimeFormatter implementation is thread-safe.)

    0 讨论(0)
  • 2021-01-14 08:35

    Or you can compare the date and put

    @Ignore("Timezone issues")
    @Test
    

    In your unit-test

    0 讨论(0)
提交回复
热议问题