In java, both the java.util
and the java.sql
package contain a Date
class, So what is the difference between them?
If one
These answers seem to be partially outdated.
I just read a little API Code (Java Version 1.8.0_91) and found this in java.sql.Date
:
/**
* Creates a date which corresponds to the day determined by the supplied
* milliseconds time value {@code theDate}.
*
* @param theDate
* a time value in milliseconds since the epoch - January 1 1970
* 00:00:00 GMT. The time value (hours, minutes, seconds,
* milliseconds) stored in the {@code Date} object is adjusted to
* correspond to 00:00:00 GMT on the day determined by the supplied
* time value.
*/
public Date(long theDate) {
super(normalizeTime(theDate));
}
/*
* Private method which normalizes a Time value, removing all low
* significance digits corresponding to milliseconds, seconds, minutes and
* hours, so that the returned Time value corresponds to 00:00:00 GMT on a
* particular day.
*/
private static long normalizeTime(long theTime) {
return theTime;
}
The method for normalizing the time is still there and even the comment says that the time will be normalized to 00:00:00 GMT but it does nothing. For some reason they removed the normalization, wich means, that a java.sql.Date
contains just like a java.util.Date
just the number of milliseconds since 1.1.1970. So there is a time component but it is not displayed externally.
For example the code
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(Calendar.getInstance().getTimeInMillis())
System.out.println(utilDate);
System.out.println(sqlDate);
produces the output
Thu Jun 02 13:17:35 CEST 2016
2016-06-02
So be careful with sql dates and do not handle them like they would just contain a Date and no time information. For example:
java.sql.Date sqlDate1 = new java.sql.Date(Calendar.getInstance().getTimeInMillis());
java.sql.Date sqlDate2 = new java.sql.Date(Calendar.getInstance().getTimeInMillis());
System.out.println(sqlDate1);
System.out.println(sqlDate2);
System.out.println(sqlDate1.equals(sqlDate2));
System.out.println(sqlDate1.toString().equals(sqlDate2.toString()));
prints:
2016-06-02
2016-06-02
false
true