繁体   English   中英

Java 8获取具有偏移量的当前日期的字符串值

[英]java 8 getting string value for current date with offset

我想以“ 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包装了很长的毫秒。 它不再像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.

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM