Java 8 optional time part not working

Viewed 812

I am trying to create date time format for optional time part currently I implemented this

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.text.ParseException;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(Ideone.getDate("2017-07-01T00:00:00.0Z"));
        System.out.println(Ideone.getDate("2017-07-01T00:00:00.00Z"));
        System.out.println(Ideone.getDate("2017-07-01T00:00:00.000Z"));
    }
    
    public static LocalDateTime getDate(String date) {
        try {
           
            DateTimeFormatter formatter2 =
                DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSS]'Z'");
            LocalDateTime ldt = LocalDateTime.parse(date, formatter2);
            
            
            return ldt;
           
        } catch (DateTimeParseException ex) {
            return null;
        }
    }
}

And having output

null

2017-07-01T00:00

2017-07-01T00:00

Now my question is, why date with 1 time fraction is not working and it is working with 2 and 3 fractions? should it entertain 1,2 and 3 fractions? or only 3 fractions?

Thanks in advance

3 Answers

Reason why you are getting null when you pass this is

"2017-07-01T00:00:00.0Z"

you have told the parser to expect 3 char format (see below .SSS)

DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSS]'Z'");

If you change it to .SS, it should work, however your last input i.e. 2017-07-01T00:00:00.000Z will break. You may want to include some logic to handle different formats

Related