gpt4 book ai didi

java - 在 Java 中计算出 Linux 纪元时间属于哪一天

转载 作者:行者123 更新时间:2023-12-01 19:35:27 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何确定给定的 Linux Epoch TS 属于哪一天。

为了帮助解释更多,我给出以下示例:

我已经使用 JODATIME 尝试过此操作,但无法获得有效的解决方案。

// some code here that I need.... <---??

// The time set here below is (Tue 2019-09-10 14:05:00 UTC)
final long timestamp = 1568124300000L


if (timestamp = xxxxx) {
System.out.println("The day it belongs to is: " + dayEpoch);
}

理想情况下,我希望打印的输出是:

The day it belongs to is: 2019-09-10

如果您提供实现此目的的代码示例,我将不胜感激:)

最佳答案

您可以使用java.time满足您的要求:

第一个选项(首选):OffsetDateTime

final long timestamp = 1568124300000L;

// create an Instant from the timestamp
Instant instant = Instant.ofEpochMilli(timestamp);
// create a datetime object from the Instant
OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(instant, ZoneId.of("UTC"));
// print it in your desired formatting
System.out.println("The day it belongs to is: "
+ offsetDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

第二个选项(有效,但不太合适):ZonedDateTime

final long timestamp = 1568124300000L;

// create an Instant from the timestamp
Instant instant = Instant.ofEpochMilli(timestamp);
// create a datetime object from the Instant
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC"));
// print it in your desired formatting
System.out.println("The day it belongs to is: "
+ zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

Please note that you can have different ZoneIds. You have clearly written that it is UTC in your case, so I took that one for the example. There is ZoneId.systemDefault(); to get a local timezone, the output for that is the same (date) on my system.
For using this, you will have to be using Java 8 or the ThreeTen-Backport

关于java - 在 Java 中计算出 Linux 纪元时间属于哪一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57872778/

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