Issue
I have an entity with field of type Date and I have annotated it with @Temporal(DATE)
.Now how do I store value in this filed? Using a set method or its automatically created?
Here's my code:
@Temporal(TemporalType.DATE)
private Date deleted_At;
java.util.Date javaDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(javaDate.getTime());
clientToDelete.setDeleted_At(sqlDate);
Is this correct?
Solution
java.time
I recommend you use java.time, the modern Java date and time API, for your date work. The class to use for a date without time of day is LocalDate
.
private LocalDate deletedAt;
(No annotation necessary.) To set it to today’s date:
clientToDelete.setDeletedAt(LocalDate.now(ZoneId.systemDefault()));
java.time is supported since Hibernate 5.
If you cannot change the type of the field, still use LocalDate
for setting the value:
clientToDelete.setDeletedAt(java.sql.Date.valueOf(
LocalDate.now(ZoneId.systemDefault())));
Do i need to set zoneid somewhere or its inbuilt?
Edit: It is never the same date in all time zones. So you need to choose in which time zone you want today’s date if that’s what you want. The JVM in which your program is running always has got a default time zone, and that’s what I am taking with ZoneId.systemDefault()
. The default time zone is typically taken from the operating system. It can also be set explicitly when you start the JVM or from within a program at any time. You may alternatively specify a time zone in the call to LocalDate.now()
, for example LocalDate.now(ZoneId.of("America/Chihuahua"))
.
Is this correct?
No, what you were doing was not entirely correct. According to the documentation a java.sql.Date
must have its time of day set to the start of the day (typically 00:00), which you don’t obtain from the code you showed us. Documentation quote:
To conform with the definition of SQL DATE, the millisecond values wrapped by a
java.sql.Date
instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
From the documentation of java.sql.Date
.
Links
- Oracle tutorial: Date Time explaining how to use java.time.
- Documentation of
java.sql.Date
.
Answered By - Ole V.V.