Convert String to LocalDate in Java

In this example, we will demonstrate how to convert String to LocalDate in Java with an example.
LocalDate represents a year-month-day in the ISO calendar and is useful for representing a date without a time. You might use a LocalDate to track a significant event, such as birth date or wedding date.

Read more about LocalDate class with an example at https://www.javaguides.net/2018/08/java-8-localdate-class-api-guide.html.

Convert String to LocalDate in Java Example

LocalDate class provides below API to convert from String to LocalDate in Java.
  • static LocalDate parse(CharSequence text) - Obtains an instance of LocalDate from a text string such as 2007-12-03.
  • static LocalDate parse(CharSequence text, DateTimeFormatter formatter) - Obtains an instance of LocalDate from a text string using a specific formatter.
package com.ramesh.java8.datetime.api;

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

/**
 * Program to demonstrate LocalDate Class APIs.
 * @author javaguides.net
 *
 */
public class LocalDateExamples {
 
    public static void main(String[] args) {
        convertStringToLocalDate();
    }

    private static void convertStringToLocalDate() {
        // ISO Date
        LocalDate localDate = LocalDate.parse("2017-05-03", DateTimeFormatter.ISO_LOCAL_DATE);
        System.out.println(localDate);

        // yyyy/MM/dd pattern
        LocalDate localDate1 = LocalDate.parse("2017/05/12", DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        System.out.println(localDate1);

        // MMM dd, yyyy pattern
        LocalDate localDate2 = LocalDate.parse("May 05, 2017", DateTimeFormatter.ofPattern("MMM dd, yyyy"));
        System.out.println(localDate2);

        // dd-MMM-yyyy pattern
        LocalDate localDate3 = LocalDate.parse("12-Jan-2017", DateTimeFormatter.ofPattern("dd-MMM-yyyy"));
        System.out.println(localDate3);

        // dd-LL-yyyy pattern
        LocalDate localDate4 = LocalDate.parse("12-01-2017", DateTimeFormatter.ofPattern("dd-LL-yyyy"));
        System.out.println(localDate4);
    }
}
Output:
2017-05-03
2017-05-12
2017-05-05
2017-01-12
2017-01-12

Reference



Comments