0

I want to cast a ZonedDateTime object into a java.sql.Timestamp object without using the local date.

For example, let's say I have the following datetime :

System.out.println(myZonedDateTime);
> 2018-09-02T23:55:05+04:00[Asia/Dubai]

And my local timezone is UTC+08:00

I try to parse my ZonedDateTime to a Timestamp :

Timestamp t = Timestamp.from(myZonedDateTime.toInstant());
System.out.println(t);
> 2018-09-03 04:55:05.0

The value I get in my timestamp depends of my local time, when I want it to depends of the ZoneId of my data.

How is it possible to do this ?

Nakeuh
  • 1,757
  • 3
  • 26
  • 65
  • 1
    First you hardly want a `Timestamp`. For your SQL database you would rather want to save an `Instant` or if that won’t work, then a `LocalDateTime`. Second, a `Timestamp` doesn’t have a time zone in it. You are getting confused by its `toString` method. When you print the `Timestamp`, you are implicitly calling `toString`. ´toStirng` in turn uses your time zone for generating the string. This fact says nothing about what is inside your `Timestamp`. Confusing? Yes, and one of the many reasons to avoid that class. – Ole V.V. Oct 23 '18 at 07:28
  • 1
    Basically, as far as possible, avoid `java.util.Date` and its derived classes. These are poorly designed classes, which old systems/applications can't get rid of, but definitely something new systems/applications should avoid. – Jai Oct 23 '18 at 07:30
  • There’s something wrong in your conversion. `23:55:05+04:00` does not equal `04:55:05+08:00`. Are you sure your local time zone was at `+08:00` on September 2? – Ole V.V. Oct 23 '18 at 07:32
  • 1
    I am using a java.sql.Timestamp because of a Framework I use (Spark SQL), so I don't really have choice here. The problem of the Timestamp being automaticaly cast into local time is confusing, but can also cause problems. In my case, I will use this timestamp to know which day of the week we are, so depending of the timezone it takes the result may change. I checked again for the weird conversion but I confirm that my local time zone was +08:00. – Nakeuh Oct 23 '18 at 08:23
  • Related: [Calendar returns date in wrong time zone](https://stackoverflow.com/questions/26678030/calendar-returns-date-in-wrong-time-zone). That question is about `Date` rather than `Timestamp`, but if I understand correctly, the problem is the same and the answer is the same. – Ole V.V. Oct 24 '18 at 11:44

0 Answers0