Time Conversion in java from SGT to UTC not working for 12:35:42

319 Views Asked by At

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.

1

There are 1 best solutions below

1
Avanika Agarwal On

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