问题描述
我有一个变量,其中包含自 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(GMT的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
这表明使用eg 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.
这篇关于从时代起,从java.util.Calendar获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!