[英]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
关于y
和u
的帖子(实际接受的问题答案)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.