簡體   English   中英

Java 模擬時間。從 GoLang 解析

[英]Java analog of time.Parse from GoLang

我正在將一段 GO 代碼重寫為 java,我對以下代碼段有疑問。

Go 代碼:

time.Parse("20060102", someString);

它是模擬的嗎?

ZonedDateTime zdt = ZonedDateTime.parse(credElements[0], DateTimeFormatter.ofPattern("yyyyMMdd")

快速查看Go 文檔可以發現:

A Time表示具有納秒級精度的瞬間。

這類似於 Java 的Instant類型。

另外,從Parse的文檔中,

布局中省略的元素假定為零,或者當零不可能時為一,因此解析“3:04pm”返回對應於 0 年 1 月 1 日 15:04:00 UTC 的時間(請注意,因為年份是0,這個時間是歸零之前的時間)。

[...]

在沒有時區指示符的情況下,Parse 返回 UTC 時間。

知道這一點,我們可以首先從不包含任何時區或時間信息的字符串中創建一個LocalDate ,然后“假設”(如 Go 文檔所稱)它在一天的開始,在 UTC 區,在為了將其轉換為Instant

var date = LocalDate.parse(someString, DateTimeFormatter.BASIC_ISO_DATE);
var instant = date.atStartOfDay(ZoneOffset.UTC).toInstant();

由於您提供的 Go 行的結果包括偏移量、區域和一天中的時間,因此您必須明確附加這些並在 Java 中使用特定的格式化程序:

public static void main(String[] args) {
    // example input
    String date = "20060102";
    // parse the date first, using a built-in formatter
    LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.BASIC_ISO_DATE);
    // then add the minimum time of day and the desired zone id
    ZonedDateTime zdt = ZonedDateTime.of(localDate, LocalTime.MIN, ZoneId.of("UTC"));
    // the formatter
    DateTimeFormatter dtfOut = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss Z VV", Locale.ENGLISH);
    // the result of the Go statement
    String expected = "2006-01-02 00:00:00 +0000 UTC";
    // print the result
    System.out.println("Expected: " + expected);
    System.out.println("Actual:   " + zdt.format(dtfOut));
}

Output:

Expected: 2006-01-02 00:00:00 +0000 UTC
Actual:   2006-01-02 00:00:00 +0000 UTC

關於yu的帖子(實際接受的問題答案)

暫無
暫無

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

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