简体   繁体   English

从epoch开始的几天获取java.util.Calendar

[英]Get java.util.Calendar from days since epoch

I have a variable containing the days since the epoch reference date of 1970-01-01 for a certain date. 我有一个变量,包含自1970-01-01 纪元参考日期以来某个日期的日期。

Does someone know the way to convert this variable to a java.util.Calendar ? 有人知道将此变量转换为java.util.Calendar吗?

Use the java.time classes in Java 8 and later. 在Java 8及更高版本中使用java.time类。 In one line: 在一行中:

LocalDate date = LocalDate.ofEpochDay(1000);

Calling ofEpochDay(long epochDay) obtains an instance of LocalDate from the epoch day count. 调用ofEpochDay(long epochDay)从纪元日计数中获取LocalDate的实例。

The following should work: 以下应该有效:

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: 关于时区的说明:

A new GregorianCalendar instance is created using the default time zone of the system the program is running on. 使用运行程序的系统的默认时区创建新的GregorianCalendar实例。 Since Epoch is relative to UTC (GMT in Java) any time zone different from UTC must be handled with care. 由于Epoch与UTC(Java中的GMT)相关,因此必须小心处理与UTC不同的任何时区。 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));

This prints 这打印

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

This demonstrates that it is not enough to use eg c.get(Calendar.DAY_OF_YEAR) . 这表明仅使用例如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")) . 在创建GregorianCalendar时,可以通过显式使用GMT来避免这种情况: 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

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. c.getTime()返回的Date仍然“关闭”的原因是toString()方法使用默认的TimeZone来构建字符串。 At the top we set this to GMT-1 so everything is normal. 在顶部我们将其设置为GMT-1,所以一切正常。

Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(0);
cal.add(Calendar.DAY_OF_MONTH, daysSinceEpoch);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM