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());
}
This is incorrect. an
OffsetDateTimerepresents 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 anOffsetDateTimeobject) 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. ItstoString()shows 6, I believe. You cannot change this.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
DateTimeFormatterobject), and you'd have to change that object. If you can't do that, you're out of options. Possibly the other code is callingtoString()- that uses some unspecified arbitrary renderer (DateTimeFormatterobject) - you should never usetoString()unless the docs explicitly spec out what it renders (rare), or for debugging purposes.Yes, this formatter will get you 3 digits.
No, this doesn't accomplish anything. This would: