编辑:代码失败的原因在@GS3给出的答案中!
我的回答提供了通常被认为是最新的替代方案:
我不建议使用java.text.SimpleDateFormat
在这里,因为您使用的是一个非常古老且几乎过时的 API,而您正在通过使用现代 API 来接收时间java.time.Clock
.
一个好的举措是使用java.time.format.DateTimeFormatter
s 用于解析,但我认为你甚至可以跳过时钟并使用OffsetDateTime.now(ZoneOffset.UTC)
.
但是,这段代码肯定会解析String
由你的第一行产生:
public static void main(String[] args) {
// your first two lines
Clock clock = Clock.systemUTC();
String clockTime = clock.instant().toString();
// a hint to the problem
System.out.println(clockTime + " <--- 6 fractions of second");
// how to parse a String like that in plain java.time
OffsetDateTime odt = OffsetDateTime.parse(clockTime);
System.out.println(odt.format(
DateTimeFormatter.ISO_OFFSET_DATE_TIME
)
);
}
其输出如下所示(显然具有不同的值):
2021-06-17T06:34:55.490370Z <--- 6 fractions of second
2021-06-17T06:34:55.49037Z
使用的输出DateTimeFormatter.ISO_OFFSET_DATE_TIME
只是一种选择,您仍然可以使用DateTimeFormatter.ofPattern(yourPatternString)
, a DateTimeFormatterBuilder
为了处理可选部分或其他内置格式化程序之一。
如果您只想获取当前时刻并将其存储在某个日期时间类中,您可以使用now()
方法中的日期时间类java.time
have:
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
看起来很适合这里,但是有一个ZonedDateTime
, too.
看看吧java.time
...