Saturday, 9 December 2017

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




Answer




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 href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#ofEpochSecond-long-int-java.time.ZoneOffset-"
rel="nofollow noreferrer">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.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...