Benjamin Benjamin - 3 months ago 14
Java Question

Java SimpleDateFormat parsing odd result

I've got a question regarding Class SimpleDateFormat.
I want to convert the format of a date string.
The date is 21.11.2011 and I want it to be converted to 111121.

This is my code:

public class Main {

private static final SimpleDateFormat oldSimpleDateFormat = new SimpleDateFormat("dd.MM.YYYY");
private static final SimpleDateFormat newSimpleDateFormat = new SimpleDateFormat("YYMMdd");
private static String oldDate = "21.11.2011";
private static Date myDate = oldSimpleDateFormat.parse(oldDate, new ParsePosition(0));
private static String newDate = newSimpleDateFormat.format(myDate);

public static void main(String[] args){
System.out.println(myDate);
System.out.println(newDate);
}
}


The results in the console are Mon Jan 03 00:00:00 CET 2011 and 110103.
So the formatting part works correctly, but the parsing part not as expected.

Answer

You are using YYYY (uppercase) when you should be using yyyy (lowercase).

Y means "Week year". y means "year".