3

以下 Java 测试在我们的美国托管构建服务器上通过。它还在非美国服务器上传递,例如在德国。它在我在爱尔兰运行的本地服务器上失败。以下代码说明了一个失败的测试。

org.junit.ComparisonFailure: expected:<[4/6/09 11:30 AM]> but was:<[06/04/09 11:30]>

有没有我可以提供的系统设置来让这些测试在本地通过?

public void testFormattedDate() {
// Set the default time zone in case this unit test is executed in a different country
TimeZone.setDefault(TimeZone.getTimeZone(DateUtil.DEFAULT_TIMEZONE));
final Date utilDate = new Date();
utilDate.setDate(6);
utilDate.setHours(11);
utilDate.setMinutes(30);
utilDate.setMonth(3);
utilDate.setSeconds(45);
utilDate.setYear(109);

SimpleDateFormat dateFormatter = new SimpleDateFormat();        
final String formattedOutput = dateFormatter.format(utilDate);

Assert.assertEquals("4/6/09 11:30 AM", formattedOutput);
}  
4

2 回答 2

4

必须尝试为SimpleDateFormat提供模式吗?

SimpleDateFormat dateFormatter = new SimpleDateFormat("d/M/yy HH:mm a");

于 2012-07-27T08:21:36.573 回答
4

时间是正确的,但SimpleDateFormat()构造函数在内部使用Locale.getDefault(). 因此,您既可以提供自己的格式,也可以提供其他语言环境,这似乎只能使用自定义格式,即使用SimpleDateFormat(String pattern, Locale locale).

问题是它SimpleDateFormat()使用了依赖于语言环境的模式,因此系统的默认语言环境可能会导致与您在美国获得的模式不同(我假设德国服务器不使用德语语言环境作为其默认设置,因为那时您应该得到一个日期如06.04.09 11:30)。

于 2012-07-27T08:24:20.620 回答