1

I need to parse specific date with joda library, I cant use an other library because its java 6 and we dont have another library available in module.

Anyway, I have this date :

2022-08-02T23:00:59Z

And I need to parse it for some operation after, but when I try to parse, I have this error :

java.lang.IllegalArgumentException: Invalid format: "2022-08-02T23:00:59Z" is malformed at "Z"

My code :

 String pattern = "yyyy-MM-dd'T'HH:mm:ss";
        String dateString="2022-08-02T23:00:59Z";
        DateTimeFormatter date = DateTimeFormat.forPattern(pattern);
        DateTime dateTIme = date.parseDateTime(dateString);

Maybe I make something wrong ?

I cannot found the good format for this pattern, so if anyone has idea, thank you very much

Bakou99
  • 11
  • 1
  • 1
    Hello, try "yyyy-MM-dd'T'HH:mm:ss'Z'" – Mar-Z Apr 24 '23 at 18:45
  • Similar: [java.time.format.DateTimeParseException: Text '2021-02-19T00:45:09.798Z' could not be parsed, unparsed text found at index 23](https://stackoverflow.com/questions/66442927/java-time-format-datetimeparseexception-text-2021-02-19t004509-798z-could-n). That question is about java.time, not Joda-Tme; but the problem is the same and the solution similar. – Ole V.V. Apr 24 '23 at 22:57
  • 1
    @Mar-Z No, incorrect. **Never put the `Z` within quotes.** The quotes mean "expect but ignore this text". You will be ignoring vital information, the offset from UTC (a number of hours-minutes-seconds). – Basil Bourque Apr 24 '23 at 23:05
  • 1
    Totally agree. I realized it later... – Mar-Z Apr 25 '23 at 08:43

1 Answers1

2

No need to define a formatting pattern at all. Your input text conforms to the ISO 8601 standard formats used by default in Joda-Time.

DateTime dt = DateTime.parse( "2022-08-02T23:00:59Z" );

Generate text from that date-time object, in ISO 8601 format.

String output = dt.toString();

2022-08-02T23:00:59.000Z


As for what is wrong with your formatting pattern: Your pattern accounts for 3 parts (date, T delimiter, time). But your input has 4 parts, those 3 plus an offset-from-UTC, the number of hours-minutes-seconds ahead or behind the temporal meridian of UTC. The character Z is an abbreviation of +00:00, for an offset of zero.


I cant use an other library because its java 6 and we dont have another library available in module

FYI, the Joda-Time library is now in maintenance-mode. It creator went on to also create its successor, the java.time classes defined in JSR 310 and bundled with Java 8+. A back-port of those classes was made to support earlier Java 6 and Java 7. See the ThreeTen-Backport project.

I recommend using that back-port rather than Joda-Time. The API of ThreeTen-Backport is nearly identical to java.time. This makes eventual migration to java.time quite simple, little more than changing import statements.

And of course, Java 6 is very much past end-of-life.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154