Date to SQLDate

I have a simple function converts date to java.sql.date.

public static java.sql.Date getSqlDate(String dateStr, String format) {
    java.sql.Date dt = null;
    Date date;
    SimpleDateFormat df = new SimpleDateFormat(format);
    ParsePosition pos = new ParsePosition(0);
    date = df.parse(dateStr, pos);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    dt = java.sql.Date.valueOf(cal.get(cal.YEAR) + "-" + (cal.get(cal.MONTH)+1)
            + "-" + cal.get(cal.DATE));
    return dt;
}

The problem is when i call this function with the following i'm getting an IllegalArgumentException.

"2008-02-04", "yyyy-dd-MM"

May be I'm not able to catch error in the code, hence wanted to have another set of eyes looking into this and correct me please...

-- M

Upvotes: 0

Views: 144

Answers (2)

KV Prajapati
KV Prajapati

Reputation: 94645

Try,

java.util.Date dt = null;
SimpleDateFormat df = new SimpleDateFormat(format);
ParsePosition pos = new ParsePosition(0);
date = df.parse(dateStr, pos);
java.sql.Date sqlDate = new java.sql.Date(date.getTime());

Upvotes: 2

David Kroukamp
David Kroukamp

Reputation: 36423

should it not be:

dt = java.sql.Date.valueOf(cal.get(cal.YEAR) + "-" + cal.get(cal.DATE)  + "-" +(cal.get(cal.MONTH)+1));

to agree with the yyyy-dd-mm format, as your code examples shows a yyyy-mm-dd format:

cal.get(cal.YEAR) + "-" + (cal.get(cal.MONTH)+1) + "-" + cal.get(cal.DATE)

Upvotes: 1

Related Questions