English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented(I)

Java Object-Oriented(II)

Java Object-Oriented(III)

Java Exception Handling

Java List(List)

Java Queue(Queue)

Java Map Collection

Java Set Collection

Java Input/Output(I/O)

Java Reader/Writer

Java other topics

Java program to convert string to date

Comprehensive Java Examples

In this program, you will learn to use formatters to convert strings to dates in Java.

Example1Use predefined formatter to convert string to date

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class TimeString {
    public static void main(String[] args) {
        //Format y-M-d or yyyy-MM-d
        String string = "2017-07-25";
        LocalDate date = LocalDate.parse(string, DateTimeFormatter.ISO_DATE);
        System.out.println(date);
    }
}

When the program is run, the output is:

2017-07-25

In the above program, we used the predefined formatter ISO_DATE, which takes date strings in the format2017-07-25or2017-07-25 + 05:45''

The parse() function of LocalDate uses the given formatter to parse the given string. You can also remove the ISO_DATE formatter in the above example and replace the parse() method with:

LocalDate date = LocalDate.parse(string, DateTimeFormatter);

Example2Use pattern formatter to convert string to date

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class TimeString {
    public static void main(String[] args) {
        String string = "July" 25, 2017";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
        LocalDate date = LocalDate.parse(string, formatter);
        System.out.println(date);
    }
}

When the program is run, the output is:

2017-07-25

In the above program, our date format is MMMM d, yyyy. Therefore, we created a formatter with the given pattern.

Now, we can use the LocalDate.parse() function to parse the date and obtain a LocalDate object.

Comprehensive Java Examples