Get java.util.Calendar from days since epoch

后端 未结 3 1650
清酒与你
清酒与你 2021-01-18 15:53

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

Does someone know the way to convert this variabl

相关标签:
3条回答
  • 2021-01-18 15:56

    Use the java.time classes in Java 8 and later. In one line:

    LocalDate date = LocalDate.ofEpochDay(1000);
    

    Calling ofEpochDay(long epochDay) obtains an instance of LocalDate from the epoch day count.

    0 讨论(0)
  • 2021-01-18 15:57
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(0);
    cal.add(Calendar.DAY_OF_MONTH, daysSinceEpoch);
    
    0 讨论(0)
  • 2021-01-18 16:10

    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. 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));
    

    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 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
    

    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.

    0 讨论(0)
提交回复
热议问题