4

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() );
    }
}
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820

2 Answers2

7

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
-3

Or you can compare the date and put

@Ignore("Timezone issues")
@Test

In your unit-test

VinhNT
  • 1,091
  • 8
  • 13