gpt4 book ai didi

java - 在时区之间转换纪元毫秒

转载 作者:行者123 更新时间:2023-11-30 05:31:24 27 4
gpt4 key购买 nike

我得到一个纪元格式的数字。 Epoch 应该是 UTC,但我得到的是 PST 时区。所以我必须修复这个值。我该怎么做?

我一开始尝试的:

  // This number represents Tuesday, July 30, 2019 1:53:19 AM UTC, 
// but it's supposed to represent PST.
// The actual PST value for this date is going to be 1564476799000
// which is the same as Tuesday, July 30, 2019 8:53:19 AM UTC.
// So I need to "pretend" that this value is actually PST
// and adjust it accordingly (including DST and friends).
Long testDateLong = 1564451599000L;

// These correctly assume that the instant is in UTC and adjust it to PST
// which is not the real intention
LocalDateTime pstL = LocalDateTime.ofInstant(Instant.ofEpochMilli(testDateLong),
ZoneId.of("America/Los_Angeles"));
ZonedDateTime pstZ = ZonedDateTime.ofInstant(Instant.ofEpochMilli(testDateLong),
ZoneId.of("America/Los_Angeles"));

System.out.println(pstL);
System.out.println(pstZ);

/*
* Output:
*
* 2019-07-29T18:53:19
* 2019-07-29T18:53:19-07:00[America/Los_Angeles]
*
* Expected to see:
*
* 2019-07-30T01:53:19
* 2019-07-30T01:53:19-07:00[America/Los_Angeles]
*
*/

可行的解决方案是将纪元值格式化为 UTC 格式的字符串,然后使用 PST 时区对其进行解析,如下所示:

  Long testDateLong = 1564451599000L;

DateTimeFormatter formatterUTC = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.SHORT)
.withZone(ZoneId.of("Etc/UTC"));

DateTimeFormatter formatterPST = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.SHORT)
.withZone(ZoneId.of("America/Los_Angeles"));

String utcString = formatterUTC.format(Instant.ofEpochMilli(testDateLong));

Instant instant = Instant.from(formatterPST.parse(utcString));

System.out.println(utcString);
System.out.println(instant);
System.out.println(instant.toEpochMilli());

/*
* Output:
*
* 7/30/19 1:53 AM
* 2019-07-30T08:53:00Z
* 1564476780000
*/

但是,对我来说这似乎是一个糟糕的解决方案(只是一种预感)。我想知道是否有比生成字符串并解析它更好的方法?

最佳答案

您可以使用UTC时区进行解析,然后更改时区

long testDateLong = 1564451599000L;
Instant ist = Instant.ofEpochMilli(testDateLong);

ZoneId zUTC = ZoneId.of("UTC");
ZoneId zLA = ZoneId.of("America/Los_Angeles");

ZonedDateTime zdt1 = LocalDateTime.ofInstant(ist, zUTC).atZone(zLA);
ZonedDateTime zdt2 = ZonedDateTime.ofInstant(ist, zUTC).withZoneSameLocal(zLA);

System.out.println(zdt1); // 2019-07-30T01:53:19-07:00[America/Los_Angeles]
System.out.println(zdt2); // 2019-07-30T01:53:19-07:00[America/Los_Angeles]

关于java - 在时区之间转换纪元毫秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57465714/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com