从纪元以来的天数获取 java.util.Calendar

2022-01-11 00:00:00 date calendar java

我有一个变量,其中包含 纪元参考日期 code>1970-01-01 某个日期.

I have a variable containing the days since the epoch reference date of 1970-01-01 for a certain date.

有人知道如何将此变量转换为 java.util.Calendar?

Does someone know the way to convert this variable to a java.util.Calendar?

推荐答案

以下应该可以:

Calendar c = new GregorianCalendar();
c.setTime(new Date(0));

c.add(Calendar.DAY_OF_YEAR, 1000);

System.err.println(c.getTime());

<小时>

关于时区的说明:


A note regarding time zones:

使用运行程序的系统的默认时区创建一个新的 GregorianCalendar 实例.由于 Epoch 与 UTC(Java 中的 GMT)相关,因此必须小心处理任何不同于 UTC 的时区.下面的程序说明了这个问题:

A new GregorianCalendar instance is created using the default time zone of the system the program is running on. Since Epoch is relative to UTC (GMT in Java) any time zone different from UTC must be handled with care. The following program illustrates the problem:

TimeZone.setDefault(TimeZone.getTimeZone("GMT-1"));

Calendar c = new GregorianCalendar();
c.setTimeInMillis(0);

System.err.println(c.getTime());
System.err.println(c.get(Calendar.DAY_OF_YEAR));

c.add(Calendar.DAY_OF_YEAR, 1);
System.err.println(c.getTime());
System.err.println(c.get(Calendar.DAY_OF_YEAR));

打印出来

Wed Dec 31 23:00:00 GMT-01:00 1969
365
Thu Jan 01 23:00:00 GMT-01:00 1970
1

这表明仅使用 e.g. 是不够的.c.get(Calendar.DAY_OF_YEAR).在这种情况下,必须始终考虑到它是一天中的什么时间.这可以通过在创建 GregorianCalendar 时显式使用 GMT 来避免:new GregorianCalendar(TimeZone.getTimeZone("GMT")).如果日历是这样创建的,则输出为:

This demonstrates that it is not enough to use e.g. c.get(Calendar.DAY_OF_YEAR). In this case one must always take into account what time of day it is. This can be avoided by using GMT explicitly when creating the GregorianCalendar: new GregorianCalendar(TimeZone.getTimeZone("GMT")). If the calendar is created such, the output is:

Wed Dec 31 23:00:00 GMT-01:00 1969
1
Thu Jan 01 23:00:00 GMT-01:00 1970
2

现在日历返回有用的值.c.getTime() 返回的 Date 仍然关闭"的原因是 toString() 方法使用了默认的 TimeZone 来构建字符串.在顶部,我们将其设置为 GMT-1,因此一切正常.

Now the calendar returns useful values. The reason why the Date returned by c.getTime() is still "off" is that the toString() method uses the default TimeZone to build the string. At the top we set this to GMT-1 so everything is normal.

相关文章