无法使用 Java 8 将给定的本地日期转换为 GMT 日期

Unable to convert a given Local Date to GMT Date using Java 8

我很难使用 Java 8 类 LocalDateTime and ZonedDateTime.

将给定的本地日期(在 IST 中)转换为 GMT

考虑以下代码片段。

LocalDateTime ldt = LocalDateTime.parse("22-1-2015 10:15:55 AM", DateTimeFormatter.ofPattern("dd-M-yyyy hh:mm:ss a"));

ZonedDateTime gmtZonedTime = ldt.atZone(ZoneId.of("GMT+00"));

System.out.println("Date (Local) : " + ldt);

System.out.println("Date (GMT) : " + gmtZonedTime);

产生以下输出:

Date (Local) : 2015-01-22T10:15:55
Date (GMT) : 2015-01-22T10:15:55

据我所知,它只是转换格式,而不是时间。

我期望的输出是这样的:(例如 GMT 比 IST 晚 5.30 小时)

Date (Local) : 2018-02-26T01:30
Date (GMT) : 2018-02-26T08:00Z[GMT]

请引导我到达那里!

LocalDateTime ldt = LocalDateTime.parse("22-1-2015 10:15:55 AM",
            DateTimeFormatter.ofPattern("dd-M-yyyy hh:mm:ss a"));

Instant instant = ldt.atZone(ZoneId.of("GMT+05:30")).toInstant(); // get instant in timeLine by mentioning the zoneId at which you have obtained the ldt

System.out.println("Date (Local) : " + ldt);

System.out.println("Date (GMT) : " + LocalDateTime.ofInstant(instant, ZoneId.of("GMT")));

输出符合您的预期。 LocalDateTime 根本没有时区,它只有某处的日期和时间(未指定)。您认为它在 IST 中的假设是错误的,事实并非如此。 atZone 方法添加时区,在本例中为 UTC/GMT,但它不会更改日期或时间。

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html

您可能想先将 LocalDateTime 转换为 IST 的 ZonedDateTime,然后将时区更改为 UTC。那应该改变时间。