-1

Trying to convert Singapore Time to UTc and need the result in OffsetDateTime. The below code works for me for all scenerios except one for 12:35..... for 12:00 noon it is somehow giving wrong results. Should be giving 8th Feb 04:35 morning but instead giving 7th Feb 16:35 . what could be the way around it

Code snippets as below

    if (dbTime == null) {
        return null;
    }
    SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    dateTimeFormatter.setTimeZone(TimeZone.getTimeZone(ZoneId.of("Asia/Singapore")));
    Instant instant = null;
    try {
        dateTimeFormatter.parse(dbTime);
        instant = dateTimeFormatter.parse(dbTime).toInstant();
    } catch (ParseException e) {
        LOGGER.warn("Could not parse ({}) to valid DateTime ", dbTime, e);
        return null;
    }
    OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.UTC);
    return offsetDateTime;
}

@Test
void canConvertSGTToUTC() {
    String sqlDate = "2023-02-08 12:35:45.0";
    var result = dateParser.parseToOffsetDateTime(sqlDate);
    assertEquals( "2023-02-08T04:35:45Z", result.toString());
}

SGT or Asia/Singapore is local system time from the servers.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Varun Yadav
  • 142
  • 1
  • 6
  • 2
    Please stop immediately to use `SimpleDateFormat`. It’s a notorious troublemaker of a class and fortunately long outdated. You’ve got `DateTimeFormatter` from java.time, the modern Java date and time API, which you can pass to `LocalDateTime.parse)CharSequence, DateTimeFormatter)` and parse methods of other modern classes. – Ole V.V. Feb 09 '23 at 05:34
  • 2
    If `dbTime` means that the date and time are coming from the SQL database, do not retrieve them as a `String` from there. Retrieve a `LocalDateTime` and save yourself from having to parse. See for example [my answer here](https://stackoverflow.com/a/54907501/5772882). – Ole V.V. Feb 09 '23 at 06:06
  • 1
    For your future questions (whether on Stack Overflow or elsewhere) I recommend that you learn [how to create a minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). I believe that the parsing error you asked about could have been demonstrated in about three lines of code, so if you can, don’t post more than that. – Ole V.V. Feb 09 '23 at 06:54

1 Answers1

0

use the "HH:mm:ss" format where "H" is 24hr format. "h" is 12hr format. should solve your problem

  • This is correct, as also stated in original question that I have linked to after you posted your answer. – Ole V.V. Feb 09 '23 at 07:43