問題描述
我有一個變量,其中包含 紀元參考日期 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.
這篇關于從紀元以來的天數獲取 java.util.Calendar的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!