How to Convert a String to Date in Java

The Date class represents a precise moment in time, down to the millisecond. Serializable, Cloneable and Comparable interfaces are implemented by the Date class in java.util package. It has constructors and methods for working with dates and times in Java. In Java, the "java.text.SimpleDateFormat" package has methods for formatting and parsing date and time. The “SimpleDateFormat” is a concrete class that inherits the “java. text. DateFormat” class for formatting and parsing dates. It’s interesting to note that formatting entails turning a date into a string, whereas parsing entails converting a string to a date. So let us start with the tutorial on How to Convert a String to Date in Java.

A data type is an attribute of data in computer science that tells the compiler or interpreter how the programmer intends to use the data. A data type limits the possible values for an expression, such as a variable or a function. It specifies how that data type’s values are saved in memory and what actions can be done on them. Integers, floating-point numbers, strings, characters, and other storage categories are included in data types.

 

What’s The Approach?

 

  • Import the “java.text.SimpleDataFormat” to the class.

 

  • Import the “java. util” package to the class.

 

  • Create a Scanner class inside the main  For eg, Scanner sc=new Scanner(System.in);

 

  • Accept the user input.

 

  • Use the Try And Catch to prevent errors from the user input.

 

 

  • Print the String value and the Date value.

 

Also Read:- How to Convert String to Char in Java

 

Java Program To Convert String to Date

/*
 * TechDecode Tutorials
 * 
 * How to Covert String to Date
 * 
 */
//Importing SimpleDateFormat
import java.text.SimpleDateFormat;
// importing util package
import java.util.*;
public class String_to_Date
{
    public static void main(String args[])
    {
        // Creation of Scanner Class
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter the Date in DD/MM/YYYY Format: ");
        //Taking the input from the user
        String s=sc.nextLine();
        // Using Try and Catch to Prevent errors by the user 
        try
        {
            // Converting string to Date format
            Date d=new SimpleDateFormat("dd/MM/yyyy").parse(s);
            // Printing the date 
            System.out.println(s+"\t"+d);          
        }
        catch (java.text.ParseException pe)
        {
            System.out.println("Sorry Wrong Input");
        }  
        
    }
}

Output:- 

Output Window of How to Convert a String to Date in Java

Leave a Reply

Your email address will not be published.