Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java parsing String to a Date returns incorrect Date

Tags:

java

jdbc

I am storing my 2 Java date types as Date and Time for a MySQL database table. I am using the SimepleDateFormat("YYYY-MM-dd") to store the date in my database and it shows up as the correct date when i go to select it. However when i try to parse it back into a util.Date and create a new Event Object, it shows up as 30/12/2012 instead of 31/05/2013 as it is in the database. The time, when parsed into a util.Date and formatted prints out correctly. I am not sure why the Date is printing the wrong date, but the time is printing the correct time.

Database

+--------+--------------+-----------+
+ EVENT1 +  2013-05-31  +  02:30:00 +
+--------+--------------+-----------+
+ EVENT2 +  2013-05-31  +  01:00:00 +
+--------+--------------+-----------+

Prints:

Event1
30/12/2012
02:30
Event2
30/12/2012
01:00
like image 547
user1352609 Avatar asked Nov 17 '25 00:11

user1352609


2 Answers

It should be yyyy-MM-dd with lower case Ys. See here for what the capital Y means...

Y returns 2012 while y returns 2011 in SimpleDateFormat

like image 161
Zutty Avatar answered Nov 19 '25 15:11

Zutty


Your pattern is wrong. (mm != MM, yyyy != YYYY ...)

Take a look at http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

like image 33
Michael Laffargue Avatar answered Nov 19 '25 14:11

Michael Laffargue