我试图使用java.util.Date作为输入,然后用它创建查询-所以我需要一个java.sql.Date。

我惊讶地发现它不能隐式或显式地进行转换——但我甚至不知道如何做到这一点,因为Java API对我来说仍然相当新。


当前回答

在我的情况下,从JXDatePicker (java日历)选择日期,并将其存储在数据库中的SQL日期类型,下面的工作很好。

java.sql.Date date = new java.sql.Date(pickedDate.getDate().getTime());

where pickedDate是JXDatePicker的对象

其他回答

这个函数将返回一个从java日期对象转换而来的SQL日期。

public static java.sql.Date convertFromJAVADateToSQLDate(
            java.util.Date javaDate) {
        java.sql.Date sqlDate = null;
        if (javaDate != null) {
            sqlDate = new Date(javaDate.getTime());
        }
        return sqlDate;
    }

对于另一个答案,你可能会遇到时间信息的问题(比较日期和意想不到的结果!)

我建议:

java.util.Calendar cal = Calendar.getInstance();
java.util.Date utilDate = new java.util.Date(); // your util date
cal.setTime(utilDate);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);    
java.sql.Date sqlDate = new java.sql.Date(cal.getTime().getTime()); // your sql date
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);

将java.util.Date转换为java.sql.Date将丢失小时、分钟和秒。所以如果可能的话,我建议你像这样使用java.sql.Timestamp:

prepareStatement.setTimestamp(1, new Timestamp(utilDate.getTime()));

要了解更多信息,您可以检查这个问题。

比较2个日期的方法。日期或sql.date)

 public static boolean isSameDay(Date a, Date b) {
    Calendar calA = new GregorianCalendar();
    calA.setTime(a);

    Calendar calB = new GregorianCalendar();
    calB.setTime(b);

    final int yearA = calA.get(Calendar.YEAR);
    final int monthA = calA.get(Calendar.MONTH);
    final int dayA = calA.get(Calendar.DAY_OF_YEAR);

    final int yearB = calB.get(Calendar.YEAR);
    final int monthB = calB.get(Calendar.MONTH);
    final int dayB = calB.get(Calendar.DAY_OF_YEAR);

    return yearA == yearB && monthA == monthB && dayA == dayB;
}

如果你在Mysql中使用一个日期列,可以传递这个日期的字符串表示

所以我使用DateFormatter类格式化它,然后将它设置为sql语句或准备语句中的字符串

下面是代码说明:

private String converUtilDateToSqlDate(java.util.Date utilDate) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String sqlDate = sdf.format(utilDate);
    return sqlDate;
}

字符串日期= converUtilDateToSqlDate(otherTransaction.getTransDate());

//然后在SQL语句中传入此日期