簡體   English   中英

將Java 8 ISO 8601持續時間表達式添加到java.util.Date

[英]Add a Java 8 ISO 8601 time duration expression to java.util.Date

我有一個像"PT20.345S""P2DT3H4M"等表達式,如https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang所述。 CharSequence-

我如何解析它,將它添加到當前時間並獲取java.util.Date對象?

兩者都不起作用:

Date d1 = Date.from(LocalDateTime.now().plus(Duration.parse(_expression)));
Date d2 = Date.from(Duration.parse(_expression).addTo(LocalDateTime.now()));
Duration amountToAdd = Duration.parse("PT20.345S");  // Represent a span of time. Here, about twenty and a third seconds.
Instant now = Instant.now() ;                        // Capture the current moment in UTC.
Instant otherMoment = now.plus(amountToAdd);         // Add the span-of-time to the current moment, for a moment in the future (or in the past if the duration is negative).
String output = otherMoment.toString():              // Generate a String in standard ISO 8601 format.

2018-06-30T19:34:47Z

從現代java.time類轉換為遺留類。

Date date1 = Date.from(otherMoment);
System.out.println(date1);

剛剛在歐洲/哥本哈根時區運行我得到:

6月30日星期六21:34:47 CEST 2018

如果我使用你的另一個示例持續時間字符串P2DT3H4M ,我得到:

星期二03月03日00:38:26 CEST 2018

或者,如果你是一個單行:

    Date date1 = Date.from(Instant.now().plus(Duration.parse("PT20.345S")));

java.util.Date類很久了,所以理想情況下你不應該有一個。 如果您還需要一個,通常是對於您無法更改或不想立即更改的舊API,您在使用java.time (現代Java日期和時間API)盡可能多地執行邏輯時正在思考,最后只轉換為Date 現代世界中Date最親近的堂兄是Instant ,並且InstantDate之間存在直接轉換,這就是我使用這個類的原因。 Instant也很可愛,不受區域偏移和時區的影響。

在您的代碼中,如果您使用ZoneOffsetLocalDateTime轉換為Instant (示例UTC,或使用ZoneOffset.systemDefault()系統默認值),第一個解決方案應該可以正常工作,如下所示:

Date d1 = Date.from(LocalDateTime.now().plus(Duration.parse(_expression)).toInstant(OffsetDateTime.now().getOffset());

但是 ,在這種情況下, LocalDateTime被錯誤地使用,因為它不代表片刻,不是時間軸上的一個點

來自javadoc

此類不存儲或表示時區。 相反,它是用於生日的日期的描述,結合在掛鍾上看到的當地時間。 如果沒有附加信息(如偏移或時區),它不能代表時間線上的瞬間。

但是, Instant是UTC時間軸上的一個時刻

該類在時間線上模擬單個瞬時點。 這可能用於在應用程序中記錄事件時間戳。

因此,如果您使用Instant,則無論時區如何,您都可以確切地知道正在引用的時刻。 由於您將處理業務邏輯,例如將時間量添加到當前時間並轉換為Date,因此這是一個方便使用的類。

 Date date1 = Date.from(Instant.now().plus(Duration.parse("PT20.345S")));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM