Search code examples
javadatetimetimestamp-with-timezone

Java - Convert a given DateTime in String to local timezone


I am reading a timestamp from a database as a string value, say:

2020-04-30T09:59:00.272-05:00

. Now i have to compare this with current timestamp in local timezone(System timezone)

What i have tried so Far:

ZonedDateTime result = ZonedDateTime.parse("2020-04-30T09:59:00.272-05:00"); System.out.println("Given : "+result); System.out.println("Given In Local: "+result.withZoneSameLocal(ZoneId.systemDefault()));

OutPut: Given : 2020-04-30T09:59:00.272-05:00 Given In Local: 2020-04-30T09:59:00.272-05:00[America/Chicago]

My Desired output is "2020-04-30T14:59:00.272"


Solution

  • You could parse the given date string as an OffsetDateTime, then change its offset and convert it to LocalDateTime as follows

        final String dateString = "2020-04-30T09:59:00.272-05:00";
        final ZonedDateTime result = ZonedDateTime.parse(dateString);
        System.out.println("Given         : " + result);
        final LocalDateTime localDateTime = OffsetDateTime.parse(dateString)
            .atZoneSameInstant(ZoneId.of("Europe/Berlin"))
            .toLocalDateTime();
        System.out.println("Given In Local: " + localDateTime);```
    

    prints

    Given         : 2020-04-30T09:59:00.272-05:00
    Given In Local: 2020-04-30T16:59:00.272
    

    Besides, you could also parse it to ZonedDateTime and then change the time zone, e.g.

    final LocalDateTime result = ZonedDateTime.parse(dateString)
            .withZoneSameInstant(ZoneId.of("Europe/Berlin"))
            .toLocalDateTime();