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

后端 未结 18 2300
梦如初夏
梦如初夏 2020-11-22 01:44

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 conver

相关标签:
18条回答
  • 2020-11-22 02:31

    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);
    
    0 讨论(0)
  • 2020-11-22 02:31

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 02:34

    This function will return a converted SQL date from java date object.

    public java.sql.Date convertJavaDateToSqlDate(java.util.Date date) {
        return new java.sql.Date(date.getTime());
    }
    
    0 讨论(0)
  • 2020-11-22 02:34

    Converting java.util.Data to java.sql.Data will loose hour, minute and second. So if it is possible, I suggest you use java.sql.Timestamp like this:

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

    For more info, you can check this question.

    0 讨论(0)
  • 2020-11-22 02:36

    You can use this method to convert util date to sql date,

    DateUtilities.convertUtilDateToSql(java.util.Date)
    
    0 讨论(0)
  • 2020-11-22 02:37

    I am a novice: after much running around this worked. Thought might be useful

         String bufDt =  bDOB.getText();  //data from form
         DateFormat dF = new SimpleDateFormat("dd-MM-yyyy"); //data in form is in this format
         Date bbdt = (Date)dF.parse(bufDt);  // string data is converted into java util date
         DateFormat dsF = new SimpleDateFormat("yyyy-MM-dd"); //converted date is reformatted for conversion to sql.date
         String ndt = dsF.format(bbdt); // java util date is converted to compatible java sql date
         java.sql.Date sqlDate=  java.sql.Date.valueOf(ndt);  // finally data from the form is convered to java sql. date for placing in database
    
    0 讨论(0)
提交回复
热议问题