1

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"?

Yellos
  • 1,657
  • 18
  • 33
pacoverflow
  • 3,726
  • 11
  • 41
  • 71
  • 2
    Are you sure that's not `java.sql.Date`? – SLaks Nov 27 '12 at 23:05
  • The VmtData.java has "import java.util.*;" It does not import anything from java.sql – pacoverflow Nov 27 '12 at 23:06
  • @pacoverflow It wouldn't be able to import `java.sql.Date` because of the collision (two separate `Date` classes imported). This means that the Date returned in the method could be returning a `java.sql.Date`, but it would be explicitly typed in the method, like `java.sql.Date date = blah;`. – FThompson Nov 27 '12 at 23:14
  • Always be specific when importing classes rather than using `import java.util.*;`. That way you are sure that you are not referring to classes from other packages. – devang Nov 27 '12 at 23:16
  • See [this question](http://stackoverflow.com/questions/9533935/how-to-force-hibernate-to-return-dates-as-java-util-date-instead-of-timestamp) for a really horrendous way to force this conversion. However, if your database is only storing dates, you're not really going to be able to get *valid* data for, e.g. hours, minutes, seconds. – ig0774 Nov 27 '12 at 23:23

2 Answers2

3

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());
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

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.

Atif
  • 942
  • 1
  • 6
  • 19