created: 2022-07-23T14:28:10+08:00
updated: 2022-07-24T11:02:23+08:00
tags:
- DateTimeAPI
- DateTimeAPI/DateTimeFormatter
Parsing and Formatting
Date-Time API 中基于时间的类提供 parse()
方法来解析包含日期和时间信息的字符串。这些类还提供了 format()
方法来格式化基于时间的对象以供显示。在这两种情况下,过程是相似的:您向 DateTimeFormatter
提供一个模式来创建一个格式化程序对象。然后将此格式化程序传递给 parse()
或 format()
方法。
DateTimeFormatter
类提供了许多预定义的格式化程序,或者您可以定义自己的格式化程序。
如果在转换过程中出现问题,则 parse()
和 format()
方法会抛出异常。因此,您的解析代码应该捕获 DateTimeParseException
错误,而您的格式代码应该捕获 DateTimeException
错误。
DateTimeFormatter 类既不可变又是线程安全的;它可以(并且应该)在适当的情况下分配给静态常量。
Parsing
LocalDate
类中的单参数 parse(CharSequence)
方法使用 ISO_LOCAL_DATE 格式化程序。
example1
String in = ...;
LocalDate date = LocalDate.parse(in, DateTimeFormatter.BASIC_ISO_DATE);
example2
String input = ...;
try {
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("MMM d yyyy");
LocalDate date = LocalDate.parse(input, formatter);
System.out.printf("%s%n", date);
}
catch (DateTimeParseException exc) {
System.out.printf("%s is not parsable!%n", input);
throw exc; // Rethrow the exception.
}
// 'date' has been successfully parsed
Formatting
format(DateTimeFormatter)
方法使用指定格式将基于时间的对象转换为字符串表示形式。
example
DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
// Leaving from San Francisco on July 20, 2013, at 7:30 p.m.
LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
ZoneId leavingZone = ZoneId.of("America/Los_Angeles");
ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone);
try {
String out1 = departure.format(format);
System.out.printf("LEAVING: %s (%s)%n", out1, leavingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", departure);
throw exc;
}
// Flight is 10 hours and 50 minutes, or 650 minutes
ZoneId arrivingZone = ZoneId.of("Asia/Tokyo");
ZonedDateTime arrival = departure.withZoneSameInstant(arrivingZone)
.plusMinutes(650);
try {
String out2 = arrival.format(format);
System.out.printf("ARRIVING: %s (%s)%n", out2, arrivingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", arrival);
throw exc;
}
if (arrivingZone.getRules().isDaylightSavings(arrival.toInstant()))
System.out.printf(" (%s daylight saving time will be in effect.)%n",
arrivingZone);
else
System.out.printf(" (%s standard time will be in effect.)%n",
arrivingZone);
result
LEAVING: Jul 20 2013 07:30 PM (America/Los_Angeles)
ARRIVING: Jul 21 2013 10:20 PM (Asia/Tokyo)
[[temporal包]]