0

I'm aware of the concept of "week year" and that parsing 17 using YY will result in a date of Jan 1, 2017, but switching to 18 will result in Dec 31, 2017 because that is a Sunday, the first day of the week of the next year, 2018.

I don't understand though why when you add in a MM that it doesn't seem to affect the outcome of the date, but doesn't throw an error either.

Example using JDK 7:

public static void main(String ...strings) throws Exception {
    testDateFormat("0218");
    testDateFormat("0418");
    testDateFormat("0618");
    testDateFormat("0818");
    testDateFormat("1018");
}

public static void testDateFormat(String baseDate) throws Exception {
    String fromFmt = "MMYY";
    String toFmt = "MM-dd-yyyy";
    SimpleDateFormat sdfSource = new SimpleDateFormat(fromFmt);
    SimpleDateFormat sdfDest = new SimpleDateFormat(toFmt);
    Date parsedDate = sdfSource.parse(baseDate);
    String output = sdfDest.format(parsedDate);
    System.out.println(output);
}

Output:

12-31-2017
12-31-2017
12-31-2017
12-31-2017
12-31-2017

Is this expected behavior? I.e. Does Java ignore the first part in the event of week years? I couldn't find any documentation on that at https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

awgtek
  • 1,483
  • 16
  • 28
  • The short answer is use a lower case 'MMyy' I am not as eloquent as this poster. https://stackoverflow.com/questions/34691582/how-does-java-week-year-really-work YY is not compatible with MM YY specifies week year. – Jesse Ivy Nov 09 '17 at 18:29
  • "is not compatible" explains it, but I was hoping to see the exact documentation that states that. – awgtek Nov 09 '17 at 18:44
  • The explanation in the docs isn't the greatest. Basically what's happening is that the first week of the year 2018 starts on 12-31-2017, which is sort of confusing but it makes sense. Since you did not provide any other compatible formats such as "w" for Week in year, it defaults to day one of week one of 2018 which happens to be the last day in 2017. https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – Jesse Ivy Nov 09 '17 at 18:55
  • FYI, you are using terrible old date-time classes that are now legacy, supplanted by the java.time classes. Also, see the *ThreeTen-Extra* project for some week-based classes. – Basil Bourque Nov 09 '17 at 20:13

0 Answers0