1

I've run into a strange behavior of SimpleDateFormat, i don't know how to deal with.

I need to parse a date in a specific format (Day of Week, then day, then Month, then Year, Then time). However, I've run into a behaviour, when parsing a date gives me a very strnge result (other date). Here is a small, self-contained example, and it's output on my machine.

public static void main(String[] args) throws Exception {
    test("E YYYY kk:mm:ss");
    test("E d YYYY kk:mm:ss");
    test("E d MMMM YYYY kk:mm:ss");
}

public static void test(String format) throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    Date now = new Date();
    System.out.println(now);
    String formattedNow = sdf.format(now);
    System.out.println(formattedNow);
    Date parsedFormattedNow = sdf.parse(formattedNow);
    String formattedParsedNow = sdf.format(parsedFormattedNow);
    System.out.println(formattedParsedNow);
    System.out.println(formattedNow.equals(formattedParsedNow));
}

Output:

Sat Apr 27 13:48:07 MSK 2013
Sat 2013 13:48:07
Sat 2013 13:48:07
true
Sat Apr 27 13:48:07 MSK 2013
Sat 27 2013 13:48:07
Sat 5 2013 13:48:07
false
Sat Apr 27 13:48:07 MSK 2013
Sat 27 April 2013 13:48:07
Sat 5 January 2013 13:48:07
false

Why do then 27 transforms into 5, and April to January?

execc
  • 1,083
  • 12
  • 25

1 Answers1

2

Well, there are two aspects here:

  • The pattern E d YYYY kk:mm:ss doesn't contain a month indicator at all. So after formatting to "Sat 27 2013 13:48:07" how are you expecting the parsing part to work out the month?
  • All your patterns use YYYY which is the week-year, not calendar year. This should usually be used with "day of week, week of week-year" patterns. If you use yyyy instead, the final pattern will work.

The only reason the first pattern appears to work is that you're not actually setting anything other than the "day of week" and the year (and time, of course). If you print out parsedFormattedNow (with no other formatting) you'll see that the parse result is actually January 5th. It's just you don't notice it, because it's still a Saturday.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194