Search code examples
javadatetimezonesimpledateformatdate-format

How to parse a Date with TimeZone with and without colon


The below code for date parse works fine for the date "2015-03-25T09:24:10.000+0530" :-

String time = "2015-03-25T09:24:10.000+0530";
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

LocalDateTime localDateTime = LocalDateTime.parse(time, timeFormatter);
System.out.println("localDateTime:"+localDateTime); 

Also, the below code works fine for the date "2015-03-25T09:24:10.000+05:30"

String time = "2015-03-25T09:24:10.000+05:30";
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

LocalDateTime localDateTime = LocalDateTime.parse(time, timeFormatter);
System.out.println("localDateTime:"+localDateTime); 

But Im trying to find a pattern which match either "2015-03-25T09:24:10.000+0530" or "2015-03-25T09:24:10.000+05:30". Is that possible without doing stuff like checking whether the input date has colon or not?

I felt adding 'X' towards ending of datePattern would help according to the doc but it didnt. https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.

Any suggestions?


Solution

  • Interesting question. You can use parseBest.

      String[] test =  {"2015-03-25T09:24:10.000+0530" , "2015-03-25T09:24:10.000+05:30" };
      for (String s : test) {
         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS[Z][XXX]");
         TemporalAccessor result = formatter.parseBest(s, ZonedDateTime::from, ZonedDateTime::from);
         System.out.println(result);
      }
    

    This outputs

    2015-03-25T09:24:10+05:30
    2015-03-25T09:24:10+05:30