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

后端 未结 2 1096
时光取名叫无心
时光取名叫无心 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.)

提交回复
热议问题