Convert datetime string in one time zone to another using offset

I have a time line "2018-01-15 01:16:00" which is in the EST time zone. I want to convert this to another timezone dynamically using a UTC offset. My javascript code passes this UTC offset as a parameter, and the servlet must convert / format this date and time string to the time zone identified by the provided offset.

I tried many approaches, including those documented in the oracle tutorials , but could not find a solution.

Below is my code that I am trying, any help is appreciated.

private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String DEFAULT_TIME_ZONE = ZoneId.SHORT_IDS.get("EST");

public static void main(String[] args) throws Exception {
    String dateTime = "2018-01-15 02:35:00";
    //parse the datetime using LocalDateTime
    LocalDateTime defaultDateTime = LocalDateTime.parse(dateTime, DateTimeFormatter.ofPattern(DATE_FORMAT));

    //get the datetime in default timezone
    ZoneId defaultZoneId = ZoneId.of(DEFAULT_TIME_ZONE);
    ZonedDateTime defaultZoneDateTime = defaultDateTime.atZone(defaultZoneId);
    System.out.println("EST time: "+defaultZoneDateTime.format(DateTimeFormatter.ofPattern(DATE_FORMAT)));
    ZonedDateTime utcZonedDateTime = defaultZoneDateTime.withZoneSameInstant(ZoneId.of("UTC"));
    String utcTime = defaultZoneDateTime.withZoneSameInstant(ZoneId.of("UTC")).format(DateTimeFormatter.ofPattern(DATE_FORMAT));
    System.out.println("UTC : "+utcTime);

    //IST timezone
    ZoneOffset offset = ZoneOffset.of("+05:30");
    OffsetDateTime offsetDate = OffsetDateTime.of(utcZonedDateTime.toLocalDateTime(), offset);
    String targetTimeZone = offsetDate.format(DateTimeFormatter.ofPattern(DATE_FORMAT));
    System.out.printf("target time : "+targetTimeZone);

}

OUTPUT

EST time: 2018-01-15 02:35:00
UTC : 2018-01-15 07:37:00
target time : 2018-01-15 07:37:00

Estimated Target Time: 2018-01-15 13:05:00

+4
source share
2

:

OffsetDateTime offsetDate = OffsetDateTime.of(utcZonedDateTime.toLocalDateTime(), offset);

, /, . .

, . :

OffsetDateTime offsetDate = utcZonedDateTime.toInstant().atOffset(offset);

, :

  • ZoneOffset.UTC - ZoneId.of("UTC")
  • EST - , , " " ( EST EDT) UTC-5. , " ", America/New_York .
  • , , . DST.

ZonedDateTime ZonedDateTime UTC. :

OffsetDateTime target = defaultZoneDateTime.toInstant().at(offset);

ZonedDateTime :

ZonedDateTime target = defaultZoneDateTime.withZoneSameInstant(offset);

, , , , .

+13

OffsetDateTime.of(utcZonedDateTime.toLocalDateTime(), offset)

. , OffsetDateTime , LocalDateTime, LocalDateTime UTC.

, , - , , , EST UTC: , :

defaultZoneDateTime.withZoneSameInstant(offset);

, OffsetDateTime, ZonedDateTime:

OffsetDateTime.ofInstant(defaultZoneDateTime.toInstant(), offset);
+5

Source: https://habr.com/ru/post/1692191/


All Articles