Java - Date and Time Parsing

What is Parsing?

Parsing is the process of creating a date, time, or datetime object from a string.

Parsing is handled by a DateTimeFormatter.

The same symbols used for formatting are also used as parsing symbols.

Methods

There are two ways to parse a string into a datetime object:

  • Using the parse() method of the datetime class
  • Using the parse() method of the DateTimeFormatter class

Exception

Runtime DateTimeParseException is thrown if the text cannot be parsed.

DateTimeParseException getErrorIndex() method returns the index in the text where the error occurred.

DateTimeParseException getParsedString() method returns the text being parsed.

Each datetime class has two overloaded versions of the parse() static method.

The return type of the parse() method is the same as the defining datetime class.

The following are the two version of the parse() method in LocalDate class:

static LocalDate parse(CharSequence text)
static LocalDate parse(CharSequence text, DateTimeFormatter formatter)

The following code parses two strings into two LocalDate objects:

Demo

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
  public static void main(String[] args) {
    // Parse a LocalDate in ISO format
    LocalDate ld1 = LocalDate.parse("2018-01-10");

    // Parse a LocalDate in MM/dd/yyyy format
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    LocalDate ld2 = LocalDate.parse("01/10/2018", formatter);

    System.out.println("ld1: " + ld1);
    System.out.println("ld2: " + ld2);
  }//from  w w w .  j  av  a  2s  .  c o  m
}

Result

Related Topics