4

I'm processing a list of dates from an input file, and I need to convert each from String to Date. Examples of the format:

9/2/2013 7:34:17 PM
1/13/2011 10:47:36 AM

Each time a line is read, the date is stored in the String variable dateAsString. Here's what I've got:

DateFormat format = new SimpleDateFormat("MM/dd/YYYY hh:mm:ss a");  
Date myDate = format.parse(dateAsString);  
System.out.println(myDate.toString());  

The output is incorrect:

9/2/2013 7:34:17 PM becomes Sun Dec 30 19:34:17 EST 2012
1/13/2011 10:47:36 AM becomes Sun Dec 26 10:47:36 EST 2010

It seems pretty straightforward, so I'm confused. What am I doing wrong?

Erica
  • 149
  • 1
  • 3
  • 7

3 Answers3

2

Just try 'yyyy' instead of 'YYYY'

Rahul T
  • 88
  • 5
2

Capital 'Y' means a "week year" where 'y' represents the actual year. Try using yyyy instead.

For more formatting help, check out the SimpleDateFormat API where they give you examples of the patterns to use.

Extra Info

Just in case you're wondering, a "week year" is a year where all the weeks in the year are whole weeks

Ascalonian
  • 14,409
  • 18
  • 71
  • 103
2

Your format is not correct, as you can see in Javadoc :

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Use yyyy instead of YYYY for the year part

Oziris
  • 176
  • 1
  • 7