我想以这种格式获取当前日期“ 2017-09-07T11:55:32 + 00:00”
但是对Java 8中的操作方法不太熟悉。

    LocalDateTime now = LocalDateTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
    String todaysDateTime = now.format(formatter);


给我一个错误

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


有人知道我该怎么做吗?

最佳答案

OffsetDateTime odt = now.atOffset(ZoneOffset.ofHoursMinutes(1, 0));
System.out.println(odt);


所有时变的toString已经给出了相应的ISO格式。

2017-11-08T15:31:04.115+01:00


但是,不是+00:00,而是Z。还会给出毫秒。因此,要么使用此标准,要么制作自己的模式。

您的格式为:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx");


其中小的x(而不是X)不进行“ Z”替换,并且冒号:需要xxx。



因此,得到的字符串可以作为(感谢@ OleV.V。):

OffsetDateTime.now(ZoneOffset.UTC)
    .format(DateTimeFormatter.‌​ofPattern("yyyy-MM-d‌​d'T'HH:mm:ssxxx"))




另一个方向:

LocalDateTime包装了很长的毫秒数,因为-count。它不再保存OffsetDateTime中的偏移量。

OffsetDateTime odt = fmt.parse(inputString);
Instant instant = odt.toInstant(); // Bare bone UTC time.
LocalDateTime ldt = LocalDateTime.ofInstant(odt.toInstant(), ZoneId.of("UTC")); // UTC too.


(这比我想象的要复杂一些。)

07-24 18:37
查看更多