OffsetDateTime 格式化和解析
OffsetDateTime formatting and parsing
这个代码
String formattedDate = OffsetDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE);
OffsetDateTime.parse(formattedDate, DateTimeFormatter.ISO_OFFSET_DATE);
导致
java.time.format.DateTimeParseException: Text '2020-11-27+01:00' could
not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor:
{OffsetSeconds=3600},ISO resolved to 2020-11-27 of type
java.time.format.Parsed
这行不通吗?
顾名思义,OffsetDateTime
也需要时间组件(小时、分钟等)。 DateTimeFormatter.ISO_OFFSET_DATE
没有时间组件的模式,因此您不应使用它来将日期字符串解析为 OffsetDateTime
。您可以使用默认时间组件构建格式化程序。
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String formattedDate = OffsetDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE);
System.out.println(formattedDate);
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_OFFSET_DATE)
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter(Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse(formattedDate, dtf);
System.out.println(odt);
System.out.println(DateTimeFormatter.ISO_OFFSET_DATE.format(odt));
}
}
输出:
2020-11-27Z
2020-11-27T00:00Z
2020-11-27Z
这个代码
String formattedDate = OffsetDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE);
OffsetDateTime.parse(formattedDate, DateTimeFormatter.ISO_OFFSET_DATE);
导致
java.time.format.DateTimeParseException: Text '2020-11-27+01:00' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {OffsetSeconds=3600},ISO resolved to 2020-11-27 of type java.time.format.Parsed
这行不通吗?
顾名思义,OffsetDateTime
也需要时间组件(小时、分钟等)。 DateTimeFormatter.ISO_OFFSET_DATE
没有时间组件的模式,因此您不应使用它来将日期字符串解析为 OffsetDateTime
。您可以使用默认时间组件构建格式化程序。
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String formattedDate = OffsetDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE);
System.out.println(formattedDate);
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_OFFSET_DATE)
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter(Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse(formattedDate, dtf);
System.out.println(odt);
System.out.println(DateTimeFormatter.ISO_OFFSET_DATE.format(odt));
}
}
输出:
2020-11-27Z
2020-11-27T00:00Z
2020-11-27Z