Home > Mobile >  Java Time conversion from string to ZonedDateTime
Java Time conversion from string to ZonedDateTime

Time:12-26

Hello I am trying to convert a Date and Time from a SQL data base that is being stored in UTC time to my systems Local Time zone that will be displayed in a table in a JAVAFX application.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

String appointmentStart = rs.getString("Start");

LocalDateTime ldtStart = LocalDateTime.parse(appointmentStart, formatter);
ZonedDateTime zdtStart = ZonedDateTime.of(ldtStart, ZoneId.systemDefault());
appointmentStart = zdtStart.format(formatter);


String appointmentEnd = rs.getString("End");

LocalDateTime ldtEnd = LocalDateTime.parse(appointmentEnd, formatter);
ZonedDateTime zdtEnd = ZonedDateTime.of(ldtEnd, ZoneId.systemDefault());
appointmentEnd = zdtEnd.format(formatter);

This is what I have written. The table is being populated in UTC time and is not converting. I get no errors but is this logic wrong? If so how can I do this?

CodePudding user response:

There may be a slicker way to do this, but here's how I would do this:

// We have an unzoned datetime String that we assume is in UTC
String appointmentStart = "2022-12-24 11:00:00";

// Add a UTC time ( 0) offset to the end of our String, and parse it to get a UTC-zoned ZonedDateTime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssZ");
ZonedDateTime utcStart = ZonedDateTime.parse(appointmentStart   " 0000", formatter);

// Convert to the local timezone
ZonedDateTime localZonedStart = utcStart.withZoneSameInstant(ZoneId.systemDefault());

// Define a formatter that doesn't include the time zone
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// Convert the local time to a String
String localZonedStartString = localZonedStart.format(formatter2);

// Print the resulting String
System.out.println(localZonedStartString);

Result:

2022-12-24 03:00:00

I'm in Pacific time zone, which is offset by -8 hours from UTC, and we see that the resulting string is correct for my local time zone.

CodePudding user response:

Welcome to Stack Overflow!

There are a couple issues with your code:

  • Look and code lines 3 and 4. You don't actually parse as UTC.
  • Since your appointmentStart string doesn't include the timezone, you need to specify that in your DateTimeFormatter.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    .withZone(ZoneOffset.UTC);

String appointmentStart = rs.getString("Start");

// UTC
ZonedDateTime ldtStart = ZonedDateTime.parse(appointmentStart, formatter);

// Local.
ZonedDateTime start = ldtStart.withZoneSameInstant(ZoneId.systemDefault());
  • Related