如何使此单元测试在所有时区中通过,无论 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() );
}
}
默认情况下,一个新的SimpleDateFormat
将使用系统默认时区。如果您想要特定时区,您应该致电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");
}
对于第二个测试,您需要将其更改为:
new DateTime(0L, DateTimeZone.UTC);
请注意,通常不应使用 staticSimpleDateFormat
变量,因为它不是线程安全的。 (而乔达时间 DateTimeFormatter
执行is线程安全。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)