我想在 UTC 中獲取 java 中的當前時間:
所以,我現在在維也納,當前當地時間是16:30:29,當前與 UTC 的偏移量是2 小時,我想得到
2022-05-27T14:30:29.813Z
以這個 Z 結尾(表示“祖魯時間”)。
有了這個
public static String getIsoUtcDate() {
Instant inst = Instant.now();
return inst.toString();
}
我明白了
2022-05-27T14:30:29.813923100Z
如何擺脫微秒?
我也試過了SimpleDateFormat
,但最后我無法得到 Z。
uj5u.com熱心網友回復:
您可以使用 aOffsetDateTime
并將其偏移量設定為 UTC。然后使用 aDateTimeFormatter
對其進行格式化。像這樣:
public static String getIsoUtcDate() {
OffsetDateTime nowUtc = OffsetDateTime.now()
.withOffsetSameInstant(ZoneOffset.UTC);
return DateTimeFormatter.ISO_DATE_TIME.format(nowUtc);
}
uj5u.com熱心網友回復:
Instant#truncatedTo
marstran的答案更加靈活。但是對于您的特定情況,有一種更簡單的方法。
String output =
Instant
.now()
.truncatedTo( ChronoUnit.MILLIS )
.toString()
;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/481915.html
上一篇:在引數化型別上使用bound