Java Program to Convert String to Date

In the previous article we have discussed Java Program to Convert String to double

In this article we will see how to convert string to Date.

Program to Convert String to Date

Before going into the program , let’s see some examples of both String and Date type.

Example-1: String types

String a = "12-06-2021;
String b = "b";
Examples-2: Date  types

LocalDate a = 1999-20-10;

Let’s see different ways to convert String to Date type.

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Method 1 : Java Program to Convert String to Date Using predefined formatters

  • In below program, we’ve used the predefined formatter “ISO_DATE” that will take date string in the format “yyyy-mm-dd” form the input.
  • The function LocalDate.parse() , parses the given string using the given formatter.

Approach :

  1. Take a String value in date format and store it in a string variable input1.
  2. Then pass that input1 variable as parameter to LocalDate.parse() method which will convert the string into date and return it .
  3. Store that LocalDate value in a variable output .
  4. Display the result .

Program:

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

public class Main

{
    public static void main(String[] args)
    {
        // creating scanner object
        Scanner sc = new Scanner(System.in);
        // input a string(date format) through scanner class
        System.out.print("Enter a string(yyyy-mm-dd) format : ");
        String input1=sc.next();
        // converting to date
        LocalDate output = LocalDate.parse(input1, DateTimeFormatter.ISO_DATE);
        System.out.println("Converted date value is : " + output);
    }
}
Output : 

Enter a string(yyyy-mm-dd) format : 1999-01-01
Converted long value is : 1999-01-01

Explore complete java concepts from the Java programming examples and get ready to become a
good programmer and crack the java software developer interview with ease.

Related Java Program: