Java Date Time - Java Dates and Times Parsing








Parsing which is handled by a DateTimeFormatter is to create a date time object from a string.

The same symbols used for formatting are used as parsing string values.

A DateTimeParseException is thrown if the text cannot be parsed. It has two methods to provide the error details. getErrorIndex() returns the error offset in the text. getParsedString() returns the text being parsed.

Both date time related classes and DateTimeFormatter defines methods to parse a string into a datetime object.

parse() method from datetime class

Each datetime class has two overloaded versions of the parse(). The return type of the parse() method is the same as the defining datetime class.

The following code shows how to use parse() methods from LocalDate objects:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/*from   w ww . j a v  a  2 s .c  o m*/
public class Main {

  public static void main(String[] args) {
    LocalDate ld1 = LocalDate.parse("2014-06-10");
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    LocalDate ld2 = LocalDate.parse("06/10/2014", formatter);

    System.out.println("ld1: " + ld1);
    System.out.println("ld2: " + ld2);
  }
}

The code above generates the following result.





parse() from DateTimeFormatter class

DateTimeFormatter class contains several parse() methods to parse strings into datetime objects.

Most of them return a TemporalAccessor object that you can query to get the datetime components.

You can pass the TemporalAccessor object to the from() method of the datetime class to get the specific datetime object.

The following code shows how to parse a string in MM/dd/yyyy format using a DateTimeFormatter object to construct a LocalDate:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
//w  ww.  j ava  2s .c o m
public class Main {

  public static void main(String[] args) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    TemporalAccessor ta = formatter.parse("06/10/2014");
    LocalDate ld = LocalDate.from(ta);
    System.out.println(ld);

  }
}

The code above generates the following result.





Example

parse() method can take a TemporalQuery to parse the string directly into a specific datetime object.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/*from ww w .ja v a2 s .  com*/
public class Main {

  public static void main(String[] args) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    LocalDate ld = formatter.parse("06/10/2014", LocalDate::from);
    System.out.println(ld);
  }
}

The code above generates the following result.

Parse Best

The DateTimeFormatter class contains a parseBest() method.

parseBest() method tries to match the string with provided format with optional format symbols.

In the following pattern we have two optional patterns.

yyyy-MM-dd['T'HH:mm:ss[Z]]

A text may be fully parsed to an OffsetDateTime, and partially parsed to a LocalDateTime and a LocalDate.

The following code shows how to use optional patterns to get best match date time objects from string.

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAccessor;
//from ww  w  . java2  s  .c  o m
public class Main {

  public static void main(String[] args) {
    DateTimeFormatter parser = DateTimeFormatter
        .ofPattern("yyyy-MM- dd['T'HH:mm:ss[Z]]");
    parseStr(parser, "2014-06-31");
    parseStr(parser, "2014-06-31T15:31:12");
    parseStr(parser, "2014-06-31T15:31:12-0500");
    parseStr(parser, "2014-06-31Hello");

  }

  public static void parseStr(DateTimeFormatter formatter, String text) {
    try {
      TemporalAccessor ta = formatter.parseBest(text, OffsetDateTime::from,
          LocalDateTime::from, LocalDate::from);
      if (ta instanceof OffsetDateTime) {
        OffsetDateTime odt = OffsetDateTime.from(ta);
        System.out.println("OffsetDateTime: " + odt);
      } else if (ta instanceof LocalDateTime) {
        LocalDateTime ldt = LocalDateTime.from(ta);
        System.out.println("LocalDateTime: " + ldt);
      } else if (ta instanceof LocalDate) {
        LocalDate ld = LocalDate.from(ta);
        System.out.println("LocalDate: " + ld);
      } else {
        System.out.println("Parsing returned: " + ta);
      }
    } catch (DateTimeParseException e) {
      System.out.println(e.getMessage());
    }
  }

}

The code above generates the following result.