gpt4 book ai didi

java - 使用 GregorianCalendar 自定义日期格式

转载 作者:行者123 更新时间:2023-11-29 08:01:50 24 4
gpt4 key购买 nike

我需要解析自定义日期格式,该格式在我需要通信的设备中定义,其中日期以从 2000 年开始计算的秒数给出。

我尝试使用 GregorianCalendar 来解析这些数据,这是我尝试过的代码:

    GregorianCalendar calendar = new GregorianCalendar();
calendar.setGregorianChange(new Date(2000 - 1900, 0, 1));

Date 对象对应于 2000 年 1 月 1 日。我认为有了这个我可以setTimeInMillis 得到正确的日期乘以我读取的时间 1000,因为它是以秒为单位计算的,而不是以毫秒为单位的 GregorianCalendar,但它没有用。我尝试了 setTimeInMillis(0),等待 calendar 对应的时间对应于 2000 年 1 月 1 日,但它没有,它对应于 1969 年 12 月 18 日。

如何配置 GregorianCalendar 以便可以 setTimeInMillis(0) 并且它对应于 2000 年 1 月 1 日?如果不可能,是否可以使用任何其他类来代替我自己创建所有代码?

提前致谢。

最佳答案

setGregorianChange 仅更改从 Julian 转换为 Gregorian 的时间点。它默认为正确的历史值。

但由于几乎所有其他人都在使用 proleptic Gregorian,因此此函数有一个有效的用例:

setGregorianChange(new Date(Long.MIN_VALUE)) //Julian never happened

这也是 JodaTime 默认使用的。

无论如何,您可以从正常的毫秒 unix 时间戳中减去 946684800000L,然后除以 1000:

public static long secondsSince2000(Date input) {
final long epoch = 946684800000L;
return (input.getTime() - epoch) / 1000L;
}

从 2000 年以来的秒数转换:

public static Calendar fromSecondsSince2000( long seconds ) {
final long epoch = 946684800000L;
Calendar cal = GregorianCalendar.getInstance();
long timestamp = epoch + seconds * 1000L;
cal.setTime(new Date(timestamp));
return cal;
}

要查看两者是否正常工作:

    long sec = secondsSince2000(new Date());
Calendar cal = fromSecondsSince2000( sec );
System.out.println(cal.getTime().toString().equals(new Date().toString()));

他们应该打印true

关于java - 使用 GregorianCalendar 自定义日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13857555/

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