Write a Java Program to Convert String to Date

Converting a string to a date is a common task in Java programming.

It allows you to manipulate and perform various operations on dates with ease.

Fortunately, Java provides a built-in class, SimpleDateFormat, which can be used to convert strings to dates.

The following is a simple Java program that demonstrates how to convert a string to a date using SimpleDateFormat.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToDate {
   public static void main(String[] args) {
      String dateStr = "2022-02-25";
      DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
      try {
         Date date = dateFormat.parse(dateStr);
         System.out.println(date);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

In the above program, we first define a string representation of the date we want to convert.

Next, we create an instance of SimpleDateFormat, passing in the format of the string representation of the date as a parameter.

In this case, we are using “yyyy-MM-dd” format, where “yyyy” represents the year, “MM” represents the month, and “dd” represents the day.

We then use the parse method of the SimpleDateFormat class to convert the string representation of the date to a Date object.

This method throws an exception if the string cannot be parsed as a date.

Therefore, we surround the parse method with a try-catch block to handle any exceptions.

Finally, we print the Date object to the console.

This is just a simple example of how to convert a string to a date using Java.

However, SimpleDateFormat provides many other options for formatting and parsing dates.

Be sure to refer to the Java documentation for more information on how to use SimpleDateFormat.