When running some tests I came across the following issue. When using:
private String printStandardDate(Date date) {
return DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.SHORT).format(date);
}
I found this produced different formats of Date depending on the location the tests where run from. So locally in windows / eclipse I got a result: 04/02/12 18:18 but on the Linux box in America I get 2/4/12 6:18 PM
This causes my Tests/Build to fail:
expected:<[04/02/12 18:18]> but was:<[2/4/12 6:18 PM]>
Could anyone explain this behavior?
That’s not strange, that’s exactly how it’s supposed to work.
The API documentation of
DateFormat.getDateTimeInstancesays:The default locale is different on your Windows system than on the Linux box in America.
If you want exact control over the date and time format, use
SimpleDateFormatand specify the format yourself. For example:Even better would be to re-use the
SimpleDateFormatobject, but beware that it is not thread-safe (if the method might be called from multiple threads at the same time, things will get messed up if those threads use the sameSimpleDateFormatobject).