In an Android project I created the following functions to output a formatted date string:
static final String INPUT_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ssZ";
public static long getDateInMilliseconds(String text) {
Date date = getDate(text, INPUT_DATE_PATTERN);
return date == null ? 0 : date.getTime();
}
public static String getFormattedDate(long dateInMillisecons) {
Date date = new Date(dateInMillisecons);
DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(
SimpleDateFormat.FULL, SimpleDateFormat.SHORT);
return dateFormat.format(date);
}
private static Date getDate(String text, String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, Locale.US);
Date date = null;
try {
date = dateFormat.parse(text);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
An example value of the text is:
"2016-04-02T09:00:00+02:00"
That means the time zone +02:00
complies with the RFC 822 time zone standard.
However, there is no way I can rely on the time zone in the string stays the same - it is served by a remote machine.
Here are two unit tests to check for the desired behavior.
@Test
public void getFormattedDateWithSummerTime() {
assertThat(DateFormatting.getFormattedDate(1459580400000L))
.isEqualTo("Saturday, April 2, 2016 9:00 AM");
}
@Test
public void getFormattedDateWithLeapYear() {
assertThat(DateFormatting.getFormattedDate(1456783200000L))
.isEqualTo("Monday, February 29, 2016 11:00 PM");
}
The tests pass on my machine. However, when I let the CI build run in the cloud they fail with the following error output:
org.junit.ComparisonFailure:
Expected :"Saturday, April 2, 2016 9:00 AM"
Actual :"Saturday, April 2, 2016 7:00 AM"org.junit.ComparisonFailure:
Expected :"Monday, February 29, 2016 11:00 PM"
Actual :"Monday, February 29, 2016 10:00 PM"