skiwi
skiwi

Reputation: 69259

Java weird behaviour on inserting date in database

I am getting some weird behaviour when inserting a date into the database.

The database uses a date field and my input is in String, so I convert it to java.util.Date and subsequently insert it.

Converting code:

private Date convertToDate(String input) {
    try {
        return new SimpleDateFormat("dd-MM-YY", Locale.ENGLISH).parse(input);
    } catch (ParseException ex) {
        Logger.getLogger(OutputProcessor.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

When input = "19-9-2011" it inserts 2010-12-26 into the database. Also when I had erroraneously set the locale to French it inserted 2011-01-03, to make it doesn't make any sense at all.

And another followup question: My program will have to deal with dates in all possible formats, I can get the locale of the user who inserts the date most likely though. How would I go on doing that?

Regards.

Upvotes: 1

Views: 99

Answers (3)

S Kr
S Kr

Reputation: 1840

use java.sql.Date if you are interacting with the database dates. Check your dateformat

Best option is to use timestamp instead of date. Store it as long (timeinmillis).

Upvotes: 0

sanbhat
sanbhat

Reputation: 17622

If you are sending input String as 19-9-2011 format should be dd-MM-yyyy and pass 2 digits for the month 09 instead of 9

Upvotes: 0

assylias
assylias

Reputation: 328598

The year is represented by small caps y, not Y:

return new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).parse(input);

Y (large cap) is the week year.

Upvotes: 5

Related Questions