I want to generate for example a date now like this format "2023-05-05T06:52:27.954Z" for with a OffsetDateTime, for calling a method in Java which require a OffsetDateTime dans the method will generate a request on a server which only accept a format of this pattern "2023-05-05T06:52:27.954Z" Do you know a mean to do that plz ? The error generated is:
expected format Value(Year,4,10,EXCEEDS_PAD)'-'Value(MonthOfYear,2)'-'Value(DayOfMonth,2)'T'Value(HourOfDay,2)':'Value(MinuteOfHour,2)':'Value(SecondOfMinute,2)Fraction(MilliOfSecond,3,3,DecimalPoint)'Z'"<EOL>}"
I tried that but nothing to do:
String dateStr = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
OffsetDateTime maintenant = OffsetDateTime.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
thank a lot and best regards
tl;dr the pattern in your
DateTimeFormatteris wrongYou have…
Zat the end, which is not in theStringto be parsed and wich would appear hard-coded in every output that is formatted by this veryDateTimeFormatterinstead of the real offsetStringwith aZfor Zulu time / UTC or any other offsetSo just replace the
'Z'by anX(and maybe useuuuufor the year)…Output (some seconds ago):
You could create an
OffsetDateTimefrom values instead of parsing aStringor invokingOffsetDateTime.now():Having this, you can print it without a formatter or even with the
DateTimeFormatterdefined above, no matter, you will get this:But that is just one representation of the values the
OffsetDateTimecontains.