How To Convert Date To String In Java

A date and time is a common requirement in many applications, so we might have to convert a date to a string in a variety of scenarios. We might need the date and time displayed on a web page, stored in a database, or generated in a report, for example. There are a few ways in Java to convert a date to a string. It’s easy to get a string representation of a date by using the toString() method in java.util.Date.

Different Approaches for converting date to string in Java

There are several ways to convert date to a string in Java:

  1. Using the `toString()` method 
  2. Using the `SimpleDateFormat` class
  3. Using the `DateTimeFormatter` class (Java 8+)

Approach 1 – Using the `toString()` method

This is the simplest method and can be used   to   quickly convert date to a string in Java. However, the resulting string may not always be in the desired format.

The first approach to convert a date to a string in Java is using the `toString()` method. This method is available for the `java.util.Date` class and returns a string representation of the date in the format “EEE MMM dd HH:mm:ss zzz yyyy”.

An example code to demonstrate the usage of the toString() method to convert a date to a string in Java:

Code:

import java.util.Date;
 public class Main {
  public static void main(String[] args) {
//Create the date object to convert into a string
	Date date = new Date();
//Define dateString variable
	String dateString = date.toString();
//Print to the console
	System.out.println("The date as a string using toString(): " + dateString);
  }
}

Output:

The date as a string using toString(): Wed Feb 09 12:30:15 GMT 2023

  Explanation:

  1. First import the `java.util.Date` class. Then,  create an instance of the `Date` class and store it in the `date` variable.
  2. The `toString()` method is called on the `date` object, which returns a string representation of the date in the format “EEE MMM dd HH:mm:ss zzz yyyy”. Finally,  print the resulting string .

Approach 2  – Using the `SimpleDateFormat` class

The second approach to convert a date to a string in Java is using the `SimpleDateFormat` class. This class provides a flexible way to format dates and times as strings. Coders can specify a format pattern using letters and symbols representing date and time elements, such as year, month, day, hour, minute, and second. The `SimpleDateFormat` class provides several predefined format patterns, but it can also define your own custom format pattern.

An example code to demonstrate the usage of the SimpleDateFormat class to convert a date to a string in Java:

Code:

import java.text.SimpleDateFormat;
import java.util.Date;
 
public class Main {
  public static void main(String[] args) {
	Date date = new Date();
//Create object and define the format
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//Define the object as its argument
	String dateString = dateFormat.format(date);
//Define the desire format
	System.out.println("The date as a string using SimpleDateFormat: " + dateString);
  }
}

Output:

The date as a string using SimpleDateFormat: 2023-02-09 12:30:15

 Explanation:

  1. First import the `java.text.SimpleDateFormat` and `java.util.Date` classes.
  2. Then, create an instance of the `Date` class and store it in the `date` variable. Next, create an instance of the `SimpleDateFormat` class and specify the format pattern “yyyy-MM-dd HH:mm:ss”.
  3. The `format()` method is called on the `dateFormat` object, passing in the `date` object, which returns a string representation of the date in the specified format. Finally, print the resulting string to the console.

Approach – 3  Using the `DateTimeFormatter` class (Java 8+)

The third approach to convert a date to a string in Java is using the `DateTimeFormatter` class introduced in Java 8. The `DateTimeFormatter` class is part of Java 8’s new date and time API and provides a more powerful and flexible way to format dates and times as strings compared to the `SimpleDateFormat` class. It supports the ISO-8601 standard and also allows defining custom format patterns.

An example code to demonstrate the usage of the DateTimeFormatter class of (Java 8+)  to convert a date to a string in Java:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
 public class Main {
  public static void main(String[] args) {
//Create an instance by using class
 LocalDateTime date = LocalDateTime.now();
//Define pattern of the instance by using class
 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	String dateString = date.format(formatter);
	System.out.println("The date as a string using DateTimeFormatter: " + dateString);
  }
}

Output:

The date as a string using DateTimeFormatter: 2023-02-09 12:30:15

 Explanation:

  1. In this code, first import the `java.time.LocalDateTime` and `java.time.format.DateTimeFormatter` classes.
  2. Then, create an instance of the `LocalDateTime` class using the `now()` method and store it in the `date` variable.
  3.  Next, create an instance of the `DateTimeFormatter` class and specify the format pattern “yyyy-MM-dd HH:mm:ss”. The `format()` method is called on the `date` object, passing in the `formatter` object, which returns a string representation of the date in the specified format. Finally, print the resulting string to the console.

Best Approach for converting date to string in java

The best approach to convert a date to a string in Java is using the DateTimeFormatter class, which is introduced in Java 8. This is the recommended approach because it is part of Java’s new date and time API and provides a more powerful and flexible way to format dates and times as strings.

The DateTimeFormatter class supports the ISO-8601 standard and allows defining custom format patterns. It provides several predefined formats, which can be used by invoking the predefined methods such as ISO_LOCAL_DATE_TIME, ISO_DATE, and ISO_INSTANT. Also, it can be used to create custom format patterns by using a combination of letters and symbols representing date and time elements, such as year, month, day, hour, minute, and second.

One significant advantage of using the DateTimeFormatter class is that it is thread-safe, unlike the SimpleDateFormat class, which is not thread-safe. Hence, using DateTimeFormatter reduces the risk of issues that could arise in a multithreaded environment.

Another advantage is that it supports different time zones, which is useful when working with dates and times across different regions.

Sample Problems for converting date to string in java

Sample Problem: Using the `toString()` method

A software company is storing the dates of employees’ hire dates in a Java `Date` object. The company needs to display these dates in a string format in the following way: “MM/dd/yyyy”. How can they convert the dates stored in the `Date` object to a string format?

import java.text.SimpleDateFormat;
import java.util.Date;
 public class DateToString {
	public static void main(String[] args) {
    	Date date = new Date();
//Create object and define the format
    	SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
//Define the object as its argument
    	String dateString = formatter.format(date);
//Define the desire format
    	System.out.println("Date in MM/dd/yyyy format: " + dateString);
	}
}

Output:

Date in MM/dd/yyyy format: 02/11/2023

  Explanation:

  1. This code first creates a Date object to represent the current date and time. Then, it creates a SimpleDateFormat object with the format “MM/dd/yyyy”.
  2. Finally, it uses the format() method to convert the Date object to a string representation in the desired format.

 Sample Problem: Using the `SimpleDateFormat` class

Write a Java program that takes a `Date` object representing a person’s birthdate and converts it to a string in the format “MMM dd, yyyy”.

import java.text.SimpleDateFormat;
import java.util.Date;
public class BirthdateToString {
    public static void main(String[] args) {
        // Create a Date object representing the person's birthdate
        Date birthdate = new Date(90, 5, 15);
        // Create a SimpleDateFormat object with the desired format
        SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");

        // Use the format method to convert the Date object to a string in the desired format
        String birthdateString = sdf.format(birthdate);

        // Print the resulting string
        System.out.println("Birthdate: " + birthdateString);
    }
}

Output:

Birthdate: Jun 15, 1990

  Explanation:

  1. Create a `Date` object representing the person’s birthdate. Then create a `SimpleDateFormat` object with the desired format “MMM dd, yyyy”.
  2. Use the `format` method of the `SimpleDateFormat` object to convert the `Date` object to a string in the desired format. Finally, we print the resulting string.
  3. Note that in this sample problem, you can use the deprecated Date constructor that takes year, month, and day as separate integers.

Sample Problem: Using the `DateTimeFormatter` class (Java 8+)

Write a Java program that takes a LocalDateTime object representing the date and time a blog post was published and converts it to a string in the format “MMMM dd, yyyy ‘at’ h:mm a”.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class BlogPostToString {
    public static void main(String[] args) {
        // Create a LocalDateTime object representing the date and time the blog post was published
        LocalDateTime blogPostDateTime = LocalDateTime.of(2023, 2, 17, 10, 30);
        // Create a DateTimeFormatter object with the desired format
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMMM dd, yyyy 'at' h:mm a");

        // Use the format method to convert the LocalDateTime object to a string in the desired format
        String blogPostDateTimeString = dtf.format(blogPostDateTime);
        // Print the resulting string
        System.out.println("Blog post published on: " + blogPostDateTimeString);
    }
}

Output:

Blog post published on: February 17, 2023 at 10:30 AM

  Explanation:

  1. First create a `LocalDateTime` object representing the date and time the blog post was published.
  2. Then create a `DateTimeFormatter` object with the desired format “MMMM dd, yyyy ‘at’ h:mm a”.
  3. Use the `format` method of the `DateTimeFormatter` object to convert the `LocalDateTime` object to a string in the desired format.
  4. Use the `format` method of the `DateTimeFormatter` object to convert the `LocalDateTime` object to a string in the desired format.

Conclusion

In conclusion, there are three main approaches to convert a date to a string in Java: the `toString()` method, the `SimpleDateFormat` class, and the `DateTimeFormatter` class. Each approach has its own strengths and weaknesses, and the best approach for a particular use case will depend on the specific requirements and constraints of the situation.

It is therefore recommended that users try all three approaches and carefully consider the factors discussed before making a final decision on the best approach for their use case.