How do I convert from MySQL DATETIME to java.time.Instant and display to user in system default timezone?

Jason Holtzen :

I'm working on a project for school and I'm at a total loss. Here is the background:

I am working on a JavaFX appointment app that will be run locally, so I don't need to worry about the ramifications of server-side timezone being different from actual user time. I cannot use any 3rd party libraries. The app currently uses a DatePicker and two ComboBox controls for the user to enter the Date, Hour, and Minute values. These are stored on an Appointment object in an Instant variable (start) with traditional get/set methods. I'm successfully writing to the DB from the controls and my results appear as I would expect. If I pick 06/31/2019 and 12:00, then write it to the DB, it shows up in the DB, stored in the Start column (which has a Datatype of DATETIME) as 2019-12-31 17:00:00. I am in CST, so my UTC offset is -5 hours. Up to this point, I believe everything is peachy.

From here, something goes south. I map each of the DB appointments to an ObservableList object using something like this on each item in the ResultSet

Instant start = i_rs.getTimestamp("start").toInstant();
Return newAppointment(start);

A value check on the Instant start variable gives me:

2019-12-31T17:00

as I would expect. However, I cannot seem to convert this time successfully to the user's timezone. The closest I have come is with this:

ZonedDateTime localStartDate = currentAppointment
            .getStart()
            .atZone(ZoneId.systemDefault());

But that returns

2019-12-31T17:00-05:00

I've also tried

ZonedDateTime zdt = date.atZone(ZoneOffset.systemDefault());

But it winds up converting my time in the wrong direction, leaving me with

2019-12-31T22:00

I've been working on this small "easy" part for over a day. Any help would be greatly appreciated.

Alexander Pavlov :
ZonedDateTime localStartDate = currentAppointment
  .getStart()
  .atZone(ZoneId.systemDefault());

Here you say "I have some timestamp, treat it as CST" It is why it becomes "17:00-05:00"

It seems you store your timestamps in UTC (if you do not then I advise you change your writing code to always store in UTC) so you should tell Java about it

ZonedDateTime localStartDate = currentAppointment
  .getStart()
  .atZone(ZoneId.of("UTC")) // my instant is UTC
  .withZoneSameInstant(ZoneId.systemDefault()) // convert to my local zone

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=158018&siteId=1