Java中的`ZonedDateTime.toInstant()`方法会转换为UTC时间。

huangapple go评论65阅读模式
英文:

Java ZonedDateTime.toInstant() moves to UTC

问题

我只想简单地将一个即时时间移动到另一个时区。

例如

2020-04-08 23:59:59.999 UTC -> 到 Europe/Sarajevo[UTC+1]

应该得到结果:
2021-04-09 00:59:59.999 UTC

它并没有返回这个结果

 dateVal.atZone(operatorTimeZone).toInstant()

返回了错误的值。

但是 dateVal.atZone(operatorTimeZone) 返回了正确的值。

不幸的是,我需要响应是 Instant。

这个问题该如何修复?

谢谢和问候,

英文:

I want simply to move an Instant moment to another time zone.

for example

2020-04-08 23:59:59.999 UTC -> to Europe/Sarajevo[UTC+1]

should result at:
2021-04-09 00:59:59.999 UTC

it does not return this

 dateVal.atZone(operatorTimeZone).toInstant()

returns wrong value.

but dateVal.atZone(operatorTimeZone) returns the right value.

unfortunantly I need the response to be Instant.

How can this be fixed?

Thanks and Regards,

答案1

得分: 1

你似乎想要做的是在时刻 dateVal 上添加时区偏移量。这可以通过获取偏移量并直接相加来实现:

ZoneOffset offset = operatorTimeZone.getRules().getOffset(i);
Instant newInstant = dateVal.plusSeconds(offset.getTotalSeconds());

另一种方法是使用 withZoneSameLocal,不过我认为这可能不够清晰地显示意图,更像是一种“技巧”。

Instant newInstant = dateVal
                        .atZone(operatorTimeZone)
                        .withZoneSameLocal(ZoneOffset.UTC)
                        .toInstant();

话虽如此,我越想越觉得这看起来像是一个 XY 问题。将结果表示为 ZonedDateTime 而不是 Instant 或许是你真正应该做的事情。

英文:

What you seem to want to do is to add the timezone's offset at the instant dateVal, to that instant. This can be done by getting the offset and adding directly:

ZoneOffset offset = operatorTimeZone.getRules().getOffset(i);
Instant newInstant = dateVal.plusSeconds(offset.getTotalSeconds());

Another way is to use withZoneSameLocal, though I think this doesn't show the intent as clearly, and is more like a "trick".

Instant newInstant = dateVal
                        .atZone(operatorTimeZone)
                        .withZoneSameLocal(ZoneOffset.UTC)
                        .toInstant();

<hr>

That said, the more I think about this, the more this looks like an XY problem. Representing the result as a ZonedDateTime rather than an Instant is probably what you really should do.

huangapple
  • 本文由 发表于 2020年4月8日 18:53:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/61098988.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定