简体   繁体   中英

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

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.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() );
    }
}

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.)

Or you can compare the date and put

@Ignore("Timezone issues")
@Test

In your unit-test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM