以下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);
} 发布于 2012-07-27 16:21:37
有没有尝试过向SimpleDateFormat提供一个模式?
SimpleDateFormat dateFormatter = new SimpleDateFormat("d/M/yy HH:mm a");
发布于 2012-07-27 16:24:21
时间是正确的,但是SimpleDateFormat()构造函数使用Locale.getDefault()在内部调用包私有构造函数。因此,您既可以提供自己的格式,也可以提供另一种语言环境,这似乎只有使用自定义格式才能实现,即使用SimpleDateFormat(String pattern, Locale locale)。
问题是SimpleDateFormat()使用了一种与区域设置相关的模式,因此系统的默认区域设置可能会导致与您在美国获得的模式不同(我假设德国服务器不使用德语区域设置作为它的默认区域设置,因为从那时起您应该得到一个像06.04.09 11:30这样的日期)。
https://stackoverflow.com/questions/11683998
复制相似问题