You can derive a timezone offset from a timezone ID but not the other way round i.e. you can not derive a timezone ID using a timezone offset; because the same timezone offset can be applicable for many timezone IDs e.g.
The following code is absolutely valid
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.parse("2007-12-03T10:15:30+01:00[Europe/Paris]");
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("MMMM dd, uuuu - HH:mm a XXX");
System.out.println(zdt.format(dtfOutput));
}
}
Output:
December 03, 2007 - 10:15 am +01:00
whereas the following code will throw exception:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
OffsetDateTime odt = OffsetDateTime.parse("2021-02-04T15:31:22.265-05:00");
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("MMMM dd, uuuu - HH:mm a z");
System.out.println(odt.format(dtfOutput));
}
}
Output:
Exception in thread "main" java.time.DateTimeException: Unable to extract ZoneId from temporal 2021-02-04T15:31:22.265-05:00
at java.base/java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:289)
at java.base/java.time.format.DateTimeFormatterBuilder$ZoneTextPrinterParser.format(DateTimeFormatterBuilder.java:4083)
at java.base/java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2343)
at java.base/java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1848)
at java.base/java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1822)
at java.base/java.time.OffsetDateTime.format(OffsetDateTime.java:1681)
at Main.main(Main.java:8)
Learn more about the modern date-time API from Trail: Date Time.
Note that the date-time API of java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…