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

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


当前回答

我正在使用以下代码,请尝试一下

DateFormat fm= new SimpleDateFormatter();

指定所需日期的格式 例如"DD-MM_YYYY"或" YYYY-mm-dd "则使用java Date数据类型为

fm.format("object of java.util.date");

然后它会解析你的日期

其他回答

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

public java.sql.Date convertJavaDateToSqlDate(java.util.Date date) {
    return new java.sql.Date(date.getTime());
}

我正在尝试以下代码,工作得很好。

java.util.Date utilDate = new java.util.Date();java.sql.date sqlDate = new java.sql.Date(utilDate);

比较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;
}

首先格式化java.util.Date。然后使用格式化的日期在java.sql.Date中获取日期

java.util.Date utilDate = "Your date"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
final String stringDate= dateFormat.format(utilDate);
final java.sql.Date sqlDate=  java.sql.Date.valueOf(stringDate);

我认为最好的转变方式是:

static java.sql.Timestamp SQLDateTime(Long utilDate) {
    return new java.sql.Timestamp(utilDate);
}

Date date = new Date();
java.sql.Timestamp dt = SQLDateTime(date.getTime());

如果你想在SQL表中插入dt变量,你可以这样做:

insert into table (expireAt) values ('"+dt+"');