Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timestamp in ISO 8601 - the last 6 digits yyyy-MM-dd'T'HH:mm:ss.?

I have timestamps looking like this:

    2015-03-21T11:08:14.859831
    2015-03-21T11:07:22.956087

I read a Wiki article on ISO 8601, but did not get the meaning of the last 6 digits here.

I tried getting it down to milliseconds using "yyyy-MM-dd'T'HH:mm:ss.sss" or "yyyy-MM-dd'T'HH:mm:ss.ssssss". Is it just more precise than milliseconds - up to microseconds?

like image 614
mel Avatar asked Jul 17 '15 13:07

mel


People also ask

How do I read ISO 8601 timestamp?

ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).

What are T and Z in timestamp?

The T is just a literal to separate the date from the time, and the Z means “zero hour offset” also known as “Zulu time” (UTC).

What is the T in ISO 8601?

Note that the "T" appears literally in the string, to indicate the beginning of the time element, as specified in ISO 8601. This profile does not specify how many digits may be used to represent the decimal fraction of a second.


1 Answers

Is it just more precise than milliseconds?

Yes, it's microseconds in this case.

ISO-8601 doesn't actually specify a maximum precision. It states:

If necessary for a particular application a decimal fraction of hour, minute or second may be included. If a decimal fraction is included, lower order time elements (if any) shall be omitted and the decimal fraction shall be divided from the integer part by the decimal sign specified in ISO 31-0, i.e. the comma [,] or full stop [.]. Of these, the comma is the preferred sign. If the magnitude of the number is less than unity, the decimal sign shall be preceded by two zeros in accordance with 3.6.

The interchange parties, dependent upon the application, shall agree the number of digits in the decimal fraction. [...]

(You very rarely actually see comma as the decimal separator - at least, that's my experience.)

Unfortunately in my experience, parsing a value like this in Java 7 is tricky - there isn't a format specifier for "just consume fractional digits and do the right thing". You may find you need to manually chop the trailing 3 digits off before parsing as milliseconds.

As Java 8 supports a precision of nanoseconds, it's rather simpler - and in fact, the built-in ISO formatter can parse it fine:

import java.time.*;
import java.time.format.*;

public class Test {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
        System.out.println(LocalDateTime.parse("2015-03-21T11:07:22.956087", formatter));
        
    }
}
like image 106
Jon Skeet Avatar answered Nov 04 '22 20:11

Jon Skeet