0

i want to get Canada/Eastern offset value from IST input date

e.g if i input 2016-03-10 10:01 then system return correct Offset is -05:00 Canada/Eastern

but when i input 2020-05-28 10:00 then i want Offset is -04:00 Canada/Eastern

thank you in adavance

 public class TimeZoneConversation {

    private static final String DATE_FORMAT = "yyyy-M-dd HH:mm";
    static ZoneId istZoneId = ZoneId.of("Asia/Kolkata");
    static ZoneId etZoneId = ZoneId.of("Canada/Eastern");

    public static void main(String[] args) {
        String dateInString = "2020-02-28 10:00";
        LocalDateTime currentDateTime = LocalDateTime.parse(dateInString, DateTimeFormatter.ofPattern(DATE_FORMAT));
        ZonedDateTime currentISTime = currentDateTime.atZone(istZoneId); //India Time
        ZonedDateTime currentETime = currentISTime.withZoneSameInstant(etZoneId); //EST Time

        System.out.println(currentISTime.toLocalDate() + "  " + currentISTime.toLocalTime() + " IST");
        System.out.println(currentETime.toLocalDate() + "  " + currentETime.toLocalTime() + " EST/Canada");

        Instant instant = Instant.now(); // Capture current moment in UTC.

        ZonedDateTime canadaTime = instant.atZone(etZoneId);

        System.out.println("Offset is " + canadaTime.getOffset() + " " + etZoneId);


    }
}

//output of above program

2020-02-28 10:00IST

2020-02-27 23:30 EST/Canada

Offset is -05:00 Canada/Eastern

Alexandru Somai
  • 1,395
  • 1
  • 7
  • 16
JDK
  • 83
  • 1
  • 12

1 Answers1

0

I don't think you should retrieve the offset from the Instant object. The right way should be to retrieve the offset from ZonedDateTime. Here is a good explanation for Instant, LocalDateTime and ZonedDateTime: What's the difference between Instant and LocalDateTime?

A working solution for your problem:

// ...
LocalDateTime currentDateTime = LocalDateTime.parse(dateInString, DateTimeFormatter.ofPattern(DATE_FORMAT));

ZonedDateTime currentISTime = currentDateTime.atZone(istZoneId); //India Time
ZonedDateTime currentETime = currentISTime.withZoneSameInstant(etZoneId); //EST Time

System.out.println(currentISTime.toLocalDate() + "  " + currentISTime.toLocalTime() + " IST");
System.out.println(currentETime.toLocalDate() + "  " + currentETime.toLocalTime() + " EST/Canada");

// apply getOffset() on ZonedDateTime, not on Instant
System.out.println("Offset is " + currentETime.getOffset() + " " + etZoneId);
  • Output for 2016-03-10 10:01 is Offset is -05:00 Canada/Eastern
  • Output for 2020-05-28 10:00 is Offset is -04:00 Canada/Eastern
Alexandru Somai
  • 1,395
  • 1
  • 7
  • 16