morm
morm

Reputation: 165

SimpleDateFormat parses a string to wrong time

I run the following code:

SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");

    try{
        Date date = sdf.parse("03-28-2003 01:00:00");
        System.out.print(date.toString());
    }
    catch(Exception e){
        //do something
    }

The result of the parsing is this date: 2003-03-28T02:00:00.000+0300

One hour is added.

When I change the year/day/hour to any other valid number, I get the correct time, no extra hour is added. If I only change the minutes or the seconds I still get the added hour.

Can anyone tell me why this happens?

EDIT:

This is related to when daylight saving time is applied in the timezone my program runs on- UTC+02:00. In this timezone the clock changed on 2003-03-28. that's why an hour was added, as it was suggested by the comments and answer below.

I used the code suggested in the answer to parse my date and the parsing worked! The date is parsed correctly, the extra hour isn't added.

Upvotes: 2

Views: 2273

Answers (1)

Anonymous
Anonymous

Reputation: 86276

Finding out exactly what your code does is complicated by the fact that not only SimpleDateFormat.parse() may depend on the default time zone of the computer (and does in this case where the pattern does not include time zone), also Date.toString() depends on the default time zone. However, I understand that you want to interpret the date string in UTC, so I will concentrate on getting the parsing right and not worry so much about what’s printed.

Feek is correct in the comment that setting the time zone of the SimpleDateFormat to UTC will get you what you want, for example:

    sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));

With this line added before try I get this output on my computer:

Fri Mar 28 02:00:00 CET 2003

2 am. CET agrees with 1 UTC, so now the parsing is correct.

Allow me to add that if you can use the Java 8 date and time classes, I find the corresponding code somewhat clearer:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss");
    LocalDateTime dateTime = LocalDateTime.parse("03-28-2003 01:00:00", formatter);
    OffsetDateTime utcDateTime = dateTime.atOffset(ZoneOffset.UTC);
    System.out.println(utcDateTime);

The point is not that it’s shorter, but that you don’t get easily in doubt about what it does and don’t easily get time zone or DST problems. An added benefit is that the output is also as expected:

2003-03-28T01:00Z

Now it’s evident that the time is correct (Z means Z or Zulu or UTC time zone, it’s got more than one name).

If for some reason you absolutely need an oldfashioned java.util.Date object, that is not difficult:

    Date date = Date.from(utcDateTime.toInstant());

This gives the same date as we got from sdf.parse() with UTC time zone.

Upvotes: 1

Related Questions