How to convert java.util.Date to java.sql.Date?

2018-12-31 04:53发布

I am trying to use a java.util.Date as input and then creating a query with it - so I need a java.sql.Date.

I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me.

17条回答
闭嘴吧你
2楼-- · 2018-12-31 05:09

try with this

public static String toMysqlDateStr(Date date) {
    String dateForMySql = "";
    if (date == null) {
        dateForMySql = null;
    } else {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateForMySql = sdf.format(date);
    }

    return dateForMySql;
}
查看更多
初与友歌
3楼-- · 2018-12-31 05:09

I think the best way to convert is:

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

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

If you want to insert the dt variable into an SQL table you can do:

insert into table (expireAt) values ('"+dt+"');
查看更多
美炸的是我
4楼-- · 2018-12-31 05:09

i am using the following code please try it out

DateFormat fm= new SimpleDateFormatter();

specify the format of the date you want for example "DD-MM_YYYY" or 'YYYY-mm-dd' then use the java Date datatype as

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

then it will parse your date

查看更多
旧人旧事旧时光
5楼-- · 2018-12-31 05:09

I was trying the following coding that worked fine.

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

查看更多
梦醉为红颜
6楼-- · 2018-12-31 05:10

If you are usgin Mysql a date column can be passed a String representation of this date

so i using the DateFormatter Class to format it and then set it as a String in the sql statement or prepared statement

here is the code illustration:

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

String date = converUtilDateToSqlDate(otherTransaction.getTransDate());

//then pass this date in you sql statement

查看更多
一个人的天荒地老
7楼-- · 2018-12-31 05:11

With the other answer you may have troubles with the time info (compare the dates with unexpected results!)

I suggest:

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);
查看更多
登录 后发表回答