使单元测试的日期在所有时区都通过,并且带/不带夏令时

Aar*_*lla 2 java timezone unit-testing

如何使该单元测试在所有时区都通过,与DST是否处于活动状态无关?

import static org.junit.Assert.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.joda.time.DateTime;
import org.junit.Test;

public class TimeZoneTest {

    private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat( "yyyy.MM.dd'T'HH:mm.ss:SSSZZ" );

    @Test
    public void testUtilDateMillis() throws Exception {
        assertEquals( "1970.01.01T00:00.00:000+0000", DATE_FORMAT.format( new Date( 0L ) ) );
    }

    @Test
    public void testDateTimeMillis() throws Exception {
        assertEquals( "1970-01-01T00:00:00.000+00:00", new DateTime( 0L ).toString() );
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

默认情况下,新用户SimpleDateFormat将使用系统默认时区。如果您想要一个特定的时区,应该调用setTimeZone它:

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");
}
Run Code Online (Sandbox Code Playgroud)

对于第二项测试,您想将其更改为:

new DateTime(0L, DateTimeZone.UTC);
Run Code Online (Sandbox Code Playgroud)

请注意,通常不应该使用静态SimpleDateFormat变量,因为它不是线程安全的。(而Joda Time DateTimeFormatter实现线程安全的。)