date - java.time.temporal.UnsupportedTemporalTypeException : Unsupported field: OffsetSeconds

标签 date exception java-8 instant localdatetime

我正在使用以下功能接口(interface)来制作通用自定义日期格式转换器。

@FunctionalInterface
public interface CustomDateFormatterInterface {
String convertStringToDate();
}

该功能接口(interface)的实现如下

CustomDateFormatterInterface customDateFormatterInterface = () -> {
                LocalDateTime localDateTime = LocalDateTime.now();
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")
                        .withLocale(Locale.getDefault())
                        .withZone(ZoneId.systemDefault());

                Instant now = Instant.now();

                String formatted = dateTimeFormatter.format(localDateTime);
                LocalDateTime parsed = dateTimeFormatter.parse(formatted, LocalDateTime::from);
                return parsed.toString();
            };

我想获取以下日期格式 2011-04-27T19:07:36+0000。但我遇到了异常(exception)。如果我尝试使用 now Instant 我得到的输出为

2020-12-29T15:44:34Z

我该怎么办,谁能告诉我哪里出错了?如果需要的话请告诉我任何其他事情。

最佳答案

使用OffsetDateTime它具有时区偏移并将其截断为秒

A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00.

OffsetDateTime offsetDateTime = OffsetDateTime.now(ZoneId.of("Europe/Paris"));

offsetDateTime.truncatedTo(ChronoUnit.SECONDS).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); //2020-12-29T18:28:44+01:00

如果您想要自定义格式,请使用 DateTimeFormatterBuilder 构建它

OffsetDateTime offsetDateTime = OffsetDateTime.now(ZoneOffset.UTC);

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
            .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
            .appendOffset("+HHMM", "+0000")
            .toFormatter();
offsetDateTime.truncatedTo(ChronoUnit.SECONDS).format(dateTimeFormatter); //2020-12-29T17:36:51+0000

关于date - java.time.temporal.UnsupportedTemporalTypeException : Unsupported field: OffsetSeconds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65494861/

相关文章:

java - 如何在 PHP 和 Java 之间传递日期?

wordpress - 发布查询,包括元数据和大于日期

java - 实现基于不同类型的谓词链接

java-8 - 当我在 Ubuntu 上构建 OpenJDK9 时,运行 "configure"并发现大量缺少的依赖项,这有关系吗?

java - 通过 lambda 表达式调用 System.out.println()

c# - 将字符串日期转换为日期

date - 在 Crystal Reports 中切换日期格式

PHP 从调用者抛出异常

java - Exceptions 与 throws 子句不兼容的原因是什么?

java - 抛出新的 IllegalOperationException Java