0

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.

Benjamin
  • 41
  • 5

2 Answers2

1

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

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

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Yes, that's it. Thank you very much! – Benjamin Aug 25 '16 at 23:48
  • Please just VTC. Here's a possible duplicate: http://stackoverflow.com/questions/27739514/simpledateformatdd-mmm-yyyy-printing-year-one-year-ahead?noredirect=1&lq=1 – Sotirios Delimanolis Aug 25 '16 at 23:50
  • Hmm.. intuitively you would assume that using `YYYY` wouldn't matter because that specific date is so far away from the end of the year. Usually you see these errors with end of December or start of January dates (as is the case in the proposed duplicate). – Mick Mnemonic Aug 25 '16 at 23:56
0

Check the javadoc for SimpleDateFormat. This is usually a problem with uppercase/lowercase letters used for different things. In this case uppercase Y is for "week year" (whatever that is) and lowercase y is for "year". Change the Y's to y's and it works.

pamcevoy
  • 1,136
  • 11
  • 15