我正在使用以下功能接口来制作通用自定义日期格式转换器。
@FunctionalInterface
public interface CustomDateFormatterInterface {
String convertStringToDate();
}
该功能接口的实现如下
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
。但我遇到了例外。如果我尝试使用 now
Instant 我得到的输出为
2020-12-29T15:44:34Z
我该怎么办,谁能告诉我哪里错了?如果需要的话请告诉我任何其他事情。
使用具有时区偏移量的OffsetDateTime并将其截断为秒
ISO-8601 日历系统中与 UTC/格林威治有偏移的日期时间,例如 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