本文介绍了使用日期在所有时区和/或DST中进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在所有时区进行此单元测试,无论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() );
}
}
推荐答案
按默认情况下,新的 SimpleDateFormat
将使用系统默认时区。如果你想要一个特定的时区,你应该在它上面调用 setTimeZone
:
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);
请注意,通常不应使用静态 SimpleDateFormat
变量,因为它不是线程安全的。(而 DateTimeFormatter
实现是线程安全的。)
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.)
这篇关于使用日期在所有时区和/或DST中进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!