What is the correct way to write date-time in ISO 8601 format when milliseconds has less than 3 digits?

69 Views Asked by At

Here is and example of date-time moment of time in ISO 8601 with milliseconds:

2024-03-02T17:13:07.123Z

What is the correct way to write date-time if case the milliseconds part consists not of 3 digits, but from smaller number of digits (the milliseconds part is less than 100 milliseconds).

For example, if the milliseconds number is 15, so 15 milliseconds past the whole second, how the string should be written?

2024-03-02T17:13:07.15Z

or

2024-03-02T17:13:07.015Z

?

And if the milliseconds part is equal to zero there are many possible ways to write it, but what is the correct one to use?

2024-03-02T17:13:07.0Z

or

2024-03-02T17:13:07.Z

or

2024-03-02T17:13:07.000Z

?

Can you please quote the relevant part of the documentation that states how this situation should be handled?

1

There are 1 best solutions below

0
Arvind Kumar Avinash On

For example, if the milliseconds number is 15, so 15 milliseconds past the whole second, how the string should be written?

The standard representation is 2024-03-02T17:13:07.015Z.

Demo using Java Language:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class Main {
    public static void main(String[] args) {
        // The second last parameter specifies nanoseconds
        OffsetDateTime odt = OffsetDateTime.of(2024, 3, 2, 17, 13, 7, 15000000, ZoneOffset.UTC);
        System.out.println(odt);
    }
}

Output:

2024-03-02T17:13:07.015Z

Online Demo

And if the milliseconds part is equal to zero there are many possible ways to write it, but what is the correct one to use?

The standard representation is 2024-03-02T17:13:07Z.

This is where a format removes the ambiguity e.g. if you use yyyy-MM-dd'T'HH:mm:ss.SSS as the format, your date-time object will be printed as 2024-03-02T17:13:07.000Z. A format is just a way to represent an object for a specific use case but a representation does not change the value e.g. you can write 5 as 5.0, 5.00, 5.000 for your specific use case and for every use case, the value will remain 5.

Demo using Java Language:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // The second last parameter specifies nanoseconds
        OffsetDateTime odt = OffsetDateTime.of(2024, 3, 2, 17, 13, 7, 0, ZoneOffset.UTC);

        // Print it in the default format
        System.out.println(odt);

        // ######### Formatted output #########
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        System.out.println(odt.format(formatter));
    }
}

Output:

2024-03-02T17:13:07Z
2024-03-02T17:13:07.000Z

Online Demo


Learn more about the modern date-time API from Trail: Date Time.