2

I've written a class which looks like this

@Entity
class Employee {

      @Column
      private String name;

      @Column
      private Date joinedDate;

}

Now, I assign value to joinedDate by doing new Date(). When I print this date, java will add the timezone correction to this. But Java will internally store time since epoch with no timezone. Let's say the local date was Wed Nov 29 18:43:43 IST 2017

When I store this object into database, what I expected to be stored was the time in GMT/UTC Zero timezone. (or at least, storing the number of milliseconds since epoch). But the value stored is Nov 29 18:43:43.

Which is wrong value. Because it's not storing the UTC time and it's not storing the timezone either. I expect within my application and DB dates should be stored in UTC timezone.

I would like to store UTC value while reading and writing instead of timezone where the application is running. My application could be running in different timezone but using the same database.

How can I achieve this?

Ganesh Satpute
  • 3,664
  • 6
  • 41
  • 78

2 Answers2

0

I think you must use the preferred type for java 8 java.time.ZonedDateTime that can storage nanosecond precisition and timezone. Also be sure that in your database the type is TIMESTAMP.

You can check out examples in this page: enter link description here

rafanegrette
  • 33
  • 1
  • 6
  • Thanks @NeoMortem for your answer. Instead of storing datetime with zone I would like to get rid off of timezone and store the date in UTC. – Ganesh Satpute Nov 30 '17 at 07:13
  • I had understood that in mysql the timestamp internally is saved in UTC instead of Timezone, but you have to set the global configuration variable or the session variable, SET GLOBAL time_zone = '+00:00';; https://dev.mysql.com/doc/refman/5.7/en/time-zone-support.html – rafanegrette Nov 30 '17 at 21:26
0

By default java uses the machine timezone for date and calendar, if you want to change it then you have the follow options

Change JVM timezone

java -Duser.timezone=Europe/Sofia com.acme.Main

Create a date instance with a different timezone

Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime()

Use java.time api

Date convertedDatetime = Date.from(datetime.atZone(ZoneId.off("UTC").toInstant());

Obs: your observation is Right, the milliseconds since epoch have not timezone but you are using a date at the database, then it does.


Update

I found that answer , it promises to change only hibernate jdbc charset

deFreitas
  • 4,196
  • 2
  • 33
  • 43