javautcoffsetdatetime

Java Current OffsetDateTime object in UTC with three digit fractional seconds (YYYY-MM-dd'T'HH:mm:ss.SSS'Z')


OffsetDateTime offsetDateTime = OffsetDateTime.now(ZoneId.of("UTC"));

Above snippet gives me six-digits fractional seconds, but I need a utility method that returns current OffsetDateTime object (not String) in UTC with three-digits format (for example: 2023-05-15T02:22:39.330Z)

Is this possible? I tried following, and still gives me six-digits fractional seconds.

    public static OffsetDateTime offsetDateTimeUtc(){
        OffsetDateTime offsetDateTime = OffsetDateTime.now(ZoneId.of("UTC"));
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd'T'HH:mm:ss.SSS'Z'");
        return OffsetDateTime.parse(offsetDateTime.toString());
    }

Solution

  • Above snippet gives me six-digits fractional seconds

    This is incorrect. an OffsetDateTime represents a time at a given offset, it does not represent any particular rendering of that time. Hence, the above snippet (Referring to the creation of an OffsetDateTime object) gives you.. an OffsetDateTime object. It does not inherently have any rendering. It is therefore incorrect to say it has a six-digit fractional second rendering. It doesn't, actually, it has 9. How many of those 9 you want depends on the call you make when rendering it. Its toString() shows 6, I believe. You cannot change this.

    returns current OffsetDateTime object (not String) in UTC with three-digits format

    Hence, this is impossible. An OffsetDateTime object does not contain any relevant info about its rendering. The code you are passing your ODT object to has its own renderer (usually, a DateTimeFormatter object), and you'd have to change that object. If you can't do that, you're out of options. Possibly the other code is calling toString() - that uses some unspecified arbitrary renderer (DateTimeFormatter object) - you should never use toString() unless the docs explicitly spec out what it renders (rare), or for debugging purposes.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd'T'HH:mm:ss.SSS'Z'");

    Yes, this formatter will get you 3 digits.

    return OffsetDateTime.parse(offsetDateTime.toString());

    No, this doesn't accomplish anything. This would:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd'T'HH:mm:ss.SSS'Z'");
    System.out.println(formatter.format(offsetDateTime));