2

Trying to parse ISO8601 using codenameone libraries for SimpleDateFormat. I'm getting the error below;

String input = "2019-08-30T00:34:34Z";
       SimpleDateFormat format = new 
       SimpleDateFormat(DateFormatPatterns.ISO8601);
       Date date = format.parse(input);     

java.lang.StringIndexOutOfBoundsException: String index out of range: -18

James N
  • 435
  • 3
  • 8
  • See https://stackoverflow.com/questions/2201925/converting-iso-8601-compliant-string-to-java-util-date – Robert Aug 29 '19 at 22:03
  • FYI, the terribly troublesome date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Aug 29 '19 at 22:30
  • 1
    All of the other answers here and these comments aren't applicable to Codename One which unfortunately doesn't have yet JSR310 – Shai Almog Aug 30 '19 at 02:25

2 Answers2

1

This is a bug with zulu time. I'm not exactly sure how this happened as this code has been there for ages but it should work with today's update.

Shai Almog
  • 51,749
  • 5
  • 35
  • 65
-1

Looking at the source code of DateFormatPatterns, ISO8601 is defined as "yyyy-MM-dd'T'HH:mm:ssZ".

Putting that into a minimal plain old Java example:

import java.util.Date;
import java.text.*;

public class DateProblem {
    public static void main(String[] args) throws Exception {
        String input = "2019-08-30T00:34:34Z";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
            // DateFormatPatterns.ISO8601
        Date date = format.parse(input);     
        System.out.println(date);
   }
}

gets me an "unparsable date" error (but not the string index error you got).

Checking the Javadoc for SimpleDateFormat shows that Z stands for RFC 822 format, that is a+ or - and 4 digits (offset in hours and minutes from GMT). Change the Z in your input to such a time zone offset, for example like this:

String input = "2019-08-30T00:34:34-0600";

This parses fine for me.

That said, the whole SimpleDateFormat et al are deprecated. You should switch to the new java.time API

Robert
  • 7,394
  • 40
  • 45
  • 64