Convert String to Date in Java

In this lesson, you will learn to convert String to LocalDate and LocalDateTime objects.

LocalDate and LocalDateTime are immutable date-time objects representing a date and a date and time. To convert String to one of the two Date objects, the provided String must represent a valid date or time according to ISO_LOCAL_DATE or ISO_LOCAL_DATE_TIME.  Otherwise, a DateTimeParseException will be thrown.

For more information on Java exception handling, check out this tutorial: Exception Handling in Java.

Convert String to the LocalDate in Java

In this example, we use the parse() method of the LocalDate class to parse the provided String.

import java.time.LocalDate;

class Test {

  public static void main(String[] args) {

    LocalDate date = LocalDate.parse("2021-08-20");

    System.out.println(date.toString());
  }
}
Output: 2021-08-20
 
We can also use the DateTimeFormatter class to specify a custom Formatter. This class is the base Formatter for printing and parsing date-time objects.

Example

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

class Test {

  public static void main(String[] args) {

    String stringDate = "August 20, 2021";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
    LocalDate dateTime = LocalDate.parse(stringDate, formatter);

    System.out.println(dateTime.toString());
  }
}
Output: 2021-08-20

Parse String to the LocalDateTime in Java

Here, we use the parse() method of the LocalDateTime class to convert the provided String to LocalDateTime.

import java.time.LocalDateTime;
class Test {

  public static void main(String[] args) {

    LocalDateTime dateTime = LocalDateTime.parse("2021-08-20T09:50:52");

    System.out.println(dateTime.toString());
  }
}
Output: 2021-08-20T09:50:52
 
Just like with the LocalDate, we can use the DateTimeFormatter class to specify a custom Formatter.

Example

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

class Test {

  public static void main(String[] args) {

    String dateTimeString = "2018-05-05 11:50:55";

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    LocalDateTime localDateTime = LocalDateTime.parse(dateTimeString, formatter);

    System.out.println(localDateTime.toString());
  }
}
Output: 2018-05-05T11:50:55
 
That was all about how to convert Java String to a Date. In the next lesson, we will cover parsing LocalDate and LocalDateTime objects to a String. 
 
Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *