简体   繁体   中英

java.util.Date.toString() is printing out wrong format

The following code prints out "vmtDataOrig.creationdate=2012-11-03"

VmtData vmtDataOrig = VmtDataDao.getInstance().loadVmt(1);
System.out.println("vmtDataOrig.creationdate=" + vmtDataOrig.getCreationDate().toString());

Here is the definition of the creationDate field in the VmtData class:

private Date creationDate = null;

Here is the hibernate mapping of the creationDate field to the database table column:

<property name="creationDate" column="CREATIONDATE" type="date"/>

The CREATIONDATE column in the MySQL database table is of type "date", and for the record retrieved it has the value "2012-11-03".

The Javadoc for the java.util.Date.toString() method says it is supposed to print the Date object in the form "dow mon dd hh:mm:ss zzz yyyy". Anyone know why it is printing it out in the form "yyyy-MM-dd"?

Even though the field is of type java.util.Date , Hibernate may well still be populating it with a java.sql.Date , which subclasses java.util.Date and overrides toString() ... For example:

public class Test {
    public static void main(String[] args) throws Exception {
        java.util.Date date = new java.sql.Date(0);
        System.out.println(date); // 1970-01-01
    }
}

It's easy to check that though:

System.out.println(vmtDataOrig.getCreationDate().getClass());

Your hibernate type is date, hence the java.sql.Date is used (which is sub-class of java.util.date). If you change hibernate type to java.sql.Timestamp, it would use its toString() implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM