0

I have searched all the way that timestamp should be stored in UTC and I am doing the same. On server startup I am setting timezone to UTC.

I have user who have default time say IST, now my question is how Date should be stored in database.

For eg user is running a job in the month of 1st of Dec 01:30 AM and in database value should go as 12/01/2017 (mm/dd/yyyy), but one thing to notice here is UTC is still 30th Nov 2017 8:00 PM (IST = UTC+5.30).

Now if I get date using java

Date date = new Date();

I will get output as 30 Nov instead of 1st Dec, so every time I do

new Date();

I have to first convert Date from UTC to user default time zone and store in database.

Please note I am saving timestamp as it is in UTC timezone

pise
  • 849
  • 6
  • 24
  • 51
  • Does the following question and answers help? [Java Best Practice for Date Manipulation/Storage for Geographically Diverse Users](https://stackoverflow.com/questions/40075780/java-best-practice-for-date-manipulation-storage-for-geographically-diverse-user)? – Ole V.V. Jan 30 '18 at 14:09
  • Is the requirement to save the date, or is it to save the point in time (timestamp)? – Ole V.V. Jan 30 '18 at 14:11
  • see https://stackoverflow.com/questions/33313991/retrieving-time-zone-of-date-stored-in-database – Laurent B Jan 30 '18 at 14:12
  • In any case I recommend you skip the long outdated `Date` class (no matter if you meant `java.util.Date` or `java.sql.Date`). [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) is so much nicer to work with. If you need to store a date, store it as `java.time.LocalDate`. If you need a point in time, use `Instant` instead. – Ole V.V. Jan 30 '18 at 14:18
  • @OleV.V. column is pure date in mysql database no time, my user is generating say for example credit card statement. – pise Jan 30 '18 at 14:26
  • @OleV.V.or instead of any person there is crone job which is generating statement for the month of Nov on 1st Dec and I want in date column of mysql value should be 12/01/2017 (mm/dd/yyyy). – pise Jan 30 '18 at 14:28
  • 1
    In that case use `LocalDate.now(ZoneId.of("Asia/Kolkata"))` to generate a `LocalDate` representing today’s date in your time zone (substitute the correct time zone if it wasn’t Asia/Kolkata). Then use `yourPreparedStatement.setObject(3, yourLocalDate)` to save the date into your column of datatype `date`. – Ole V.V. Jan 30 '18 at 14:29
  • @OleV.V. this is my question, should I stored pure date in user based timezone LocalDate.now(ZoneId.of("Asia/Kolkata")) and not in UTC, because if I store in UTC then while retrieving data with date as where condition will give wrong result since there is no timezone in pure date column. – pise Jan 30 '18 at 14:32
  • It depends on the requirements, so I cannot tell. – Ole V.V. Jan 30 '18 at 14:51

0 Answers0