How to create a OffsetDateTime in java with format 2023-05-05T06:52:27.954Z

78 Views Asked by At

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

1

There are 1 best solutions below

2
deHaar On

tl;dr the pattern in your DateTimeFormatter is wrong

You have…

  • an escaped Z at the end, which is not in the String to be parsed and wich would appear hard-coded in every output that is formatted by this very DateTimeFormatter instead of the real offset
  • no offset or zone in the pattern, which therefore won't produce a String with a Z for Zulu time / UTC or any other offset

So just replace the 'Z' by an X (and maybe use uuuu for the year)…

public static void main(String[] args) {
    try {
    // get "now" in UTC
    OffsetDateTime maintenant = OffsetDateTime.now(ZoneOffset.UTC);
    // print it formatted implicitly (toString)
    System.out.println(maintenant);
    // define a formatter for your desired format
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSX");
    // print the OffsetDateTime formatted as desired
    System.out.println(maintenant.format(dtf));
}

Output (some seconds ago):

2023-10-24T13:56:42.954882Z
2023-10-24T13:56:42.954Z

You could create an OffsetDateTime from values instead of parsing a String or invoking OffsetDateTime.now():

OffsetDateTime odt = OffsetDateTime.of(2023, 5, 5, 6, 52, 27, 954000000, ZoneOffset.UTC);

Having this, you can print it without a formatter or even with the DateTimeFormatter defined above, no matter, you will get this:

2023-05-05T06:52:27.954Z

But that is just one representation of the values the OffsetDateTime contains.