Java Program to Convert String to Date

In this program, you’ll learn to convert string to date in Java using formatter.

To understand this example, you should have the knowledge of the following Java programming topics:

Example 1: Convert String to Date using predefined formatters

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);
}
}

Output

2017-07-25

In the above program, we’ve used the predefined formatter ISO_DATE that takes date string in the format 2017–07–25 or 2017–07–25+05:45'.

The LocalDate’s parse() function parses the given string using the given formatter. You can also remove the ISO_DATE formatter in the above example and replace the parse() method with:

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

Example 2: Convert String to Date using pattern formatters

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);
}
}

Output

2017-07-25

In the above program, our date is in the format MMMM d, yyyy. So, we create a formatter of the given pattern. Check all DateTimeFormatter patterns, if you're interested.

Now, we can parse the date using LocalDate.parse() function and get the LocalDate object.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Amazon Interview : Reorder Data in Log Files

Python — Least Frequent Character in String

How I’m Teaching Myself Computer Science using Notion & OSSU (FREE TEMPLATE!!)

HTB: “Sense” Walkthrough

What is Coding? Overview and Mindsets

Azure Dev Challenge and Benefits

Optical Text Recognition in iOS 13

How to Deploy Machine Learning Model

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
LearnWithSathya

LearnWithSathya

More from Medium

JAVA /Super Keyword

Sample Apps: Spring data MongoDB and JSF Integration tutorial (PART 1)