Damo
Damo

Reputation: 1709

Date Formatting Issue

The following Java test passes on our US hosted build server. It also passes on non-US servers, e.g. in Germany. It fails on my local server, which is running in Ireland. The following code illustrates a failing test.

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

Is there a system setting I can provide to get these tests passing locally?

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);
}  

Upvotes: 3

Views: 326

Answers (2)

Thomas
Thomas

Reputation: 88707

The time is correct but the SimpleDateFormat() constructor internally calls a package private construtor using Locale.getDefault(). Thus you either can provide a format of your own or provide another locale, which seems to only be possible with a custom format, i.e. using SimpleDateFormat(String pattern, Locale locale).

The problem is that SimpleDateFormat() uses a locale dependent pattern, thus the system's default locale might result in a different pattern than what you get in the USA (I assume the German server doesn't use the German locale as its default since then you should get a date like 06.04.09 11:30).

Upvotes: 4

Olivier.Roger
Olivier.Roger

Reputation: 4249

Have to tried to provide a pattern to the SimpleDateFormat ?

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

Upvotes: 4

Related Questions