从输入的IST日期和时间中获取加拿大/东部偏移量



我想从IST输入日期获得加拿大/东部偏移值

例如,如果我输入2016-03-10 10:01,则系统返回正确的偏移为-05:00加拿大/东部

但当我输入2020-05-28 10:00时,我希望偏移量是-04:00加拿大/东部

感谢先进的

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);

}
}

//上述程序的输出

2020-02-28 10:00IST

2020-02-27美国东部时间23:30/加拿大

偏移为-05:00加拿大/东部

我认为您不应该从Instant对象中检索偏移量。正确的方法应该是从ZonedDateTime中检索offset。以下是对InstantLocalDateTimeZonedDateTime的一个很好的解释:What';Instant和LocalDateTime有什么区别?

您的问题的有效解决方案:

// ...
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);
  • 2016-03-10 10:01的输出偏移量为-05:00加拿大/东部
  • 22020-05-28 10:00的输出偏移量为-04:00加拿大/东部

最新更新