Java parsing String to a Date returns incorrect Date

我是研究僧i 提交于 2021-01-27 15:58:50

问题


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

回答1:


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




回答2:


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

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




回答3:


try

String testDate = "2007-11-02T14:46:03";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = formatter.parse(testDate);

But better way to store in database is to use timestamp instead of storing date and time separately




回答4:


The proper method is rs.getDate(int). Take a look at http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#getDate(int)

With that method you get a java.sql.Date and if you want to transform it to a java.util.Date take a look at this Converting java.sql.Date to java.util.Date

You can even do this

Date date =  rs.getTimestamp(2);

By the way, is better to have your date object independent on the format you want to use to show it.




回答5:


try this...

SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");   
Date date =  dateFormat.parse(rs.getDate(2).toString());


来源:https://stackoverflow.com/questions/16854518/java-parsing-string-to-a-date-returns-incorrect-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!