Search code examples
javadatetimetimedata-conversioniso8601

ISO8601 format in java given seconds


How do I get a string in Java in ISO8601 given the number of seconds since the epoch? I'm having trouble finding it anywhere.

I want the format to look something like this: 2000-06-31T19:22:15Z

Using just Date d = new Date(# of milliseconds from my # of seconds) gives me a date in 1970 when I should be getting something in 2000.


Solution

  • The main problem you are probably having, is that June 2000 only had 30 days. That being said instead of using Date, you could use a LocalDateTime with LocalDateTime.ofEpochSecond(long, int, ZoneOffset) like

    long epochSecond = 962392935L;
    int nanoOfSecond = 0;
    ZoneOffset offset = ZoneOffset.UTC;
    LocalDateTime ldt = LocalDateTime.ofEpochSecond(epochSecond, nanoOfSecond, offset);
    System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").format(ldt));
    

    Which should be all you need to see

    2000-06-30T19:22:15Z
    

    which is like your requested output.