简体   繁体   English

Java 模拟时间。从 GoLang 解析

[英]Java analog of time.Parse from GoLang

I am rewriting piece of GO code to java and I have doubths about the following snippet.我正在将一段 GO 代码重写为 java,我对以下代码段有疑问。

Go code: Go 代码:

time.Parse("20060102", someString);

Is it analog of?它是模拟的吗?

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

A quick look at the Go documentation reveals that:快速查看Go 文档可以发现:

A Time represents an instant in time with nanosecond precision. A Time表示具有纳秒级精度的瞬间。

Which is similar to Java's Instant type.这类似于 Java 的Instant类型。

Also, from the docs of Parse ,另外,从Parse的文档中,

Elements omitted from the layout are assumed to be zero or, when zero is impossible, one, so parsing "3:04pm" returns the time corresponding to Jan 1, year 0, 15:04:00 UTC (note that because the year is 0, this time is before the zero Time).布局中省略的元素假定为零,或者当零不可能时为一,因此解析“3:04pm”返回对应于 0 年 1 月 1 日 15:04:00 UTC 的时间(请注意,因为年份是0,这个时间是归零之前的时间)。

[...] [...]

In the absence of a time zone indicator, Parse returns a time in UTC.在没有时区指示符的情况下,Parse 返回 UTC 时间。

Knowing this, we can first create a LocalDate from your string that does not contain any zone or time information, then "assume" (as the Go documentation calls it) that it is at the start of day, and at the UTC zone, in order to convert it to an Instant :知道这一点,我们可以首先从不包含任何时区或时间信息的字符串中创建一个LocalDate ,然后“假设”(如 Go 文档所称)它在一天的开始,在 UTC 区,在为了将其转换为Instant

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

Since the result of the line of Go you provided includes an offset, a zone and the time of day, you will have to explicitly attach those and use a specific formatter in Java:由于您提供的 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: Output:

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

Posts about y and u (actually accepted answers to the questions)关于yu的帖子(实际接受的问题答案)

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

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