Converting java.sql.Date to java.util.Date

后端 未结 6 2068
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 06:07

What\'s the simplest way to convert a java.sql.Date object to a java.util.Date while retaining the timestamp?

I tried:

java.util.Date newDate = new D         


        
相关标签:
6条回答
  • 2020-12-05 06:45

    If you really want the runtime type to be util.Date then just do this:

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

    Brian.

    0 讨论(0)
  • 2020-12-05 06:46

    The class java.sql.Date is designed to carry only a date without time, so the conversion result you see is correct for this type. You need to use a java.sql.Timestamp to get a full date with time.

    java.util.Date newDate = result.getTimestamp("VALUEDATE");
    
    0 讨论(0)
  • 2020-12-05 06:49

    In the recent implementation, java.sql.Data is an subclass of java.util.Date, so no converting needed. see here: https://docs.oracle.com/javase/1.5.0/docs/api/java/sql/Date.html

    0 讨论(0)
  • 2020-12-05 06:59

    Since java.sql.Date extends java.util.Date, you should be able to do

    java.util.Date newDate = result.getDate("VALUEDATE");
    
    0 讨论(0)
  • 2020-12-05 07:08

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

    public static java.util.Date convertFromSQLDateToJAVADate(
                java.sql.Date sqlDate) {
            java.util.Date javaDate = null;
            if (sqlDate != null) {
                javaDate = new Date(sqlDate.getTime());
            }
            return javaDate;
        }
    
    0 讨论(0)
  • 2020-12-05 07:10

    From reading the source code, if a java.sql.Date does actually have time information, calling getTime() will return a value that includes the time information.

    If that is not working, then the information is not in the java.sql.Date object. I expect that the JDBC drivers or the database is (in effect) zeroing the time component ... or the information wasn't there in the first place.

    I think you should be using java.sql.Timestamp and the corresponding resultset methods, and the corresponding SQL type.

    0 讨论(0)
提交回复
热议问题