Write a Java program to convert a string to date


This program takes a date string in a specific format, parses it using a DateTimeFormatter object, and converts it into a LocalDate object for further processing.

  • import java.time.*; : This imports the java.time package which contains classes for working with dates, times, and other related data.
  • import java.util.*; : This imports the java.util package which contains various utility classes for working with collections, input/output, and other functionalities.
  • import java.time.format.DateTimeFormatter; : This imports the DateTimeFormatter class from the java.time.format package which is used to format dates and times in a specific pattern.
  • class String_ToDate: This is the class declaration.
  • public static void main(String[] args): This is the main method declaration which is the entry point of the program.
  • String str_date = "July 8, 2014";: This initializes a String variable str_date with a date string in the format of "Month day, year".
  • DateTimeFormatter date_format = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH); : This creates a DateTimeFormatter object date_format which specifies the pattern of the date string to be parsed. The pattern is "MMMM d, yyyy" which corresponds to the format of the str_date variable. The Locale.ENGLISH specifies the locale of the formatter.
  • LocalDate dt = LocalDate.parse(str_date, date_format);: This uses the parse method of the LocalDate class to parse the str_date string using the date_format formatter and create a LocalDate object dt.
  • System.out.println("String Date : "+str_date); : This prints the original date string str_date.
  • System.out.println("Convert String to Date : "+dt); : This prints the dt object which is the LocalDate representation of the str_date string.

Source Code

import java.time.*;
import java.util.*;
import java.time.format.DateTimeFormatter;
class String_ToDate
{
	public static void main(String[] args)
	{
		String str_date = "July 8, 2014";
		DateTimeFormatter date_format = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
		LocalDate dt = LocalDate.parse(str_date, date_format);
		System.out.println("String Date : "+str_date);
		System.out.println("Convert String to Date : "+dt);
	}
}

Output

String Date : July 8, 2014
Convert String to Date : 2014-07-08

Example Programs