日期到SQL日期

时间:2012-07-02 12:15:44

标签: java

我有一个简单的函数将date转换为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;
}

问题是当我用以下函数调用此函数时,我得到IllegalArgumentException

“2008-02-04”,“yyyy-dd-MM”

可能是我无法捕捉到代码中的错误,因此想要另外一组眼睛调查并纠正我...

- M

2 个答案:

答案 0 :(得分:2)

尝试,

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());

答案 1 :(得分:1)

不应该是:

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

同意yyyy-dd-mm格式,因为您的代码示例显示了yyyy-mm-dd格式:

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