SimpleDateFormat returning wrong time

92AlanC :

I'm trying to parse a date/time string with SimpleDateFormat but the output I'm getting is an hour later than expected.

Code

fun formatDate(dateString: String): String {
    val locale = Locale.ENGLISH
    val time = SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy", locale).parse(dateString)?.time

    return SimpleDateFormat("dd/MM/yyyy HH:mm", locale).format(time)
}

Test

@Test
fun shouldFormatDate() {
    val dateString = "Wed Mar 31 23:13:44 +0000 2010"
    val expected = "31/03/2010 23:13"

    assertThat(formatDate(dateString)).isEqualTo(expected)
}

Output

expected: 31/03/2010 23:13
but was : 01/04/2010 00:13

I tried using ISO-8601 time zone formatting (X instead of Z) but it didn't work either.

Any help will be much appreciated

Thomas Kläger :

Your input define a timezone offset to GMT of +0000 - for the input the locales timezone doesn't matter.

Your output however uses the timezone offset in effect on 2010-03-31 23:12 GMT in the ENGLISH locale timezone. On first of April 2010 the ENGLISH locale uses Daylight Savings Time, which has a timezone offset +0100, meaning is one hour later than GMT.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=356105&siteId=1