PeakGen
PeakGen

Reputation: 23025

Invalid date is being saved in MySQL

Please have a look at the below code

SimpleDateFormat format = new SimpleDateFormat("dd-mm-yyyy");
Date parse = format.parse("05-10-2014");
java.sql.Date sqlDate = new java.sql.Date(parse.getTime());

The output "should be" 05-10-2014, but I get the output as 2014-01-05. What is wrong here?

Even when I save the sqlDate in database, it is still being saved as 2014-01-05.

UPDATE

I changed the dd-mm-yyyy to dd-MM-yyyy. Now, mysql saves it as 2014-05-10

Upvotes: 1

Views: 160

Answers (1)

paxdiablo
paxdiablo

Reputation: 881533

If you're worried about the formatting of your dates, the java.sql.Date toString() method, the one that's called when you println it, always formats the date to be yyyy-mm-dd.

If you want to format your dates in a more controlled manner, you can use DateFormat when outputting it.

However, the real problem here (bad data) is that you're using lower-case m which is the format character for "minute in hour", not "month in year". See the SimpleDateFormat page for detail:

Letter  Date or Time Component  Presentation  Examples
------  ----------------------  ------------  --------
  M     Month in year           Month         July; Jul; 07
  m     Minute in hour          Number        30

In that second link above, the description for pards() has this little snippet:

This parsing operation uses the calendar to produce a Date. All of the calendar's date-time fields are cleared before parsing, and the calendar's default values of the date-time fields are used for any missing date-time information.

Since the default value for Calendar is January 1, 1970, and you're only setting the day, minute and year, you're ending up with January 5, 2014 (ten minutes past midnight), assuming UTC.

Changing the format string to "dd-MM-yyyy" should fix the immediate problem.

Upvotes: 4

Related Questions