How to Convert String to Date

JavaJavaBeginner
Practice Now

Introduction

In software development, it is common to store dates in plain text format and then convert them to actual dates for business logic. In Java, we have various classes to change dates in string format to the actual date. This provides us the ability to perform different manipulations on dates later. In this lab, we will review the steps to convert string to date in Java.

Import Required Packages

Import the required packages, java.text.SimpleDateFormat and java.util.Date, at the beginning of the file.

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

Create a SimpleDateFormat object

Create a SimpleDateFormat object and pass in the string format for the date that you will be converting from a string to a date. This string format must match the format of the date in the string that you will be converting.

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

Convert String to Date

Use the parse method of the SimpleDateFormat class to convert the date string to a date object.

String dateString = "01/01/2022";
Date date = dateFormat.parse(dateString);

Output Converted Date

Output the converted date using the System.out.println method. If we want to print the converted date in a specific format, we can use another SimpleDateFormat object to define the new format.

System.out.println("Original Date: " + dateString);
System.out.println("Converted Date: " + date);

SimpleDateFormat newDateFormat = new SimpleDateFormat("MMMM dd, yyyy");
System.out.println("Converted Date in New Format: " + newDateFormat.format(date));

Compile and Run

Compile StringToDate.java and run the program in the terminal using the following commands:

javac StringToDate.java
java StringToDate

Summary

In this lab, we have walked through the steps of converting a string into a date in Java. We used the SimpleDateFormat class to define the format of the date in the string, convert the string to a date object using the parse method, and outputted the converted date. This process is useful when we want to manipulate dates in our code. Be sure to follow the steps provided to successfully convert a string to a date in Java.

Other Java Tutorials you may like