How To Convert Date Format In Java

In Java, date format conversion refers to the process of converting a date object from one format to another. Java provides a built-in package called java.text.SimpleDateFormat for formatting and parsing dates in a specific pattern.

Converting a date object to a different format, you can create an instance of the SimpleDateFormat class with the desired date format pattern, and then call the format() method on the instance, passing in the date object to be formatted as a parameter.

Why conversion to data format is required in Java

Conversion to date format is required in Java for several reasons, including:

  • Data representation: Date and time values are represented in different formats depending on the region, language, and culture. Converting a date to a specific format can help ensure that the date is correctly represented and easily understood by users.
  • Data manipulation: Dates are often manipulated and compared in software applications, and different formats can affect the accuracy of the results. Converting dates to a standard format can help ensure consistent manipulation and comparison of dates.
  • Data storage: Dates are often stored in databases or files, and different systems may use different date formats. Converting dates to a standard format can help ensure compatibility and consistency across different systems.
  • Data transmission: Dates may need to be transmitted between different systems, and different systems may use different date formats. Converting dates to a standard format can help ensure compatibility and accuracy during transmission.
  • Displaying data: Dates may need to be displayed in a specific format for users to understand, such as in reports or user interfaces. Converting dates to a specific format can help ensure that the date is displayed in a way that is easily understood by users.

Method for Converting Data Format in Java

Methods for converting date format in Java includes:

  1. SimpleDateFormat class
  2. DateTimeFormatter class
  3. DateFormat class
  4. String.format() method
  5. Java 8 Date/Time API

Here is the description of each of method along with code and explanation of code that can help you in understanding each method in details:

Approach 1: SimpleDateFormat class

This class is part of the java.text package and is used to format dates into a desired format. The class provides methods to convert date to string and vice versa. You can create an instance of the SimpleDateFormat class and specify the pattern for the date format.

Code:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
    public static void main(String[] args) {
        // create a SimpleDateFormat object with the original date format
        SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        // create a SimpleDateFormat object with the desired date format
        SimpleDateFormat desiredFormat = new SimpleDateFormat("dd/MM/yyyy");
        // example string representing the original date
        String originalDateString = "2023-02-23T14:30:00.000+0000";
        try {
            // parse the original date string into a Date object using the original format
            Date originalDate = originalFormat.parse(originalDateString);
            // format the Date object into a string using the desired format
            String desiredDateString = desiredFormat.format(originalDate);
            // print the resulting string with the desired format
            System.out.println("Original date: " + originalDateString);
            System.out.println("Desired date format: " + desiredDateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Output:

Original date: 2023-02-23T14:30:00.000+0000
Desired date format: 23/02/2023

Explanation of the code:

  • The first step is to import the required packages. In this case, we only need to import java.text.ParseException, java.text.SimpleDateFormat, and java.util.Date.
  • Next, we create a class DateFormatExample with a main method.
  • We then create two SimpleDateFormat objects – one with the original date format (yyyy-MM-dd’T’HH:mm:ss.SSSZ) and another with the desired date format (dd/MM/yyyy).
  • We also create an example string representing the original date (2023-02-23T14:30:00.000+0000).
  • Inside a try-catch block, we parse the original date string into a Date object using the original format (originalFormat.parse(originalDateString)).
  • We then format the Date object into a string using the desired format (desiredFormat.format(originalDate)).
  • Finally, we print the original date string and the resulting string with the desired format to the console.

Approach 2: DateTimeFormatter class

This is a new class introduced in Java 8 and is part of the java.time package. It is similar to SimpleDateFormat but offers better thread safety and immutability. You can create an instance of the DateTimeFormatter class and specify the pattern for the date format.

Code:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatterExample {
    public static void main(String[] args) {
        // create a LocalDateTime object with the current date and time
        LocalDateTime dateTime = LocalDateTime.now();
             // create a DateTimeFormatter object with the desired output format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
               // format the LocalDateTime object using the DateTimeFormatter object
        String formattedDateTime = dateTime.format(formatter);
               // print the formatted date and time
        System.out.println("Formatted Date and Time: " + formattedDateTime);
    }
}

Output:

2023/02/22 14:10:15

Explanation of code:

  • The LocalDateTime class is used to represent a date and time without a time zone in the ISO-8601 calendar system.
  • The DateTimeFormatter class is used to format and parse date-time objects in a specific pattern.
  • In this example, we first create a LocalDateTime object with the current date and time using the now() method.
  • Next, we create a DateTimeFormatter object with the desired output format using the ofPattern() method. In this example, the output format is set to “yyyy/MM/dd HH:mm:ss”.
  • We then format the LocalDateTime object using the format() method of the DateTimeFormatter object, which returns a formatted string.
  • Finally, we print the formatted date and time using System.out.println() method.

Approach 3: DateFormat class

This is an abstract class and is part of the java.text package. It provides methods to format dates into strings and parse strings into dates. You can create an instance of the DateFormat class and specify the pattern for the date format.

Code:

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

public class DateFormatExample {
    public static void main(String[] args) {
        // Create a Date object with the initial date format
        String dateString = "2022-02-23";
        DateFormat initialFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = initialFormat.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        
        // Convert the Date object to a new date format
        DateFormat newFormat = new SimpleDateFormat("dd/MM/yyyy");
        String newDateString = newFormat.format(date);
        
        // Print the original and converted date strings
        System.out.println("Original date string: " + dateString);
        System.out.println("New date string: " + newDateString);
    }
}

Output:

Original date string: 2022-02-23
New date string: 23/02/2022

Explanation of code:

  • The code imports the necessary classes for date formatting: DateFormat, SimpleDateFormat, Date, and ParseException.
  • The main method creates a Date object with the initial date format using the SimpleDateFormat class. In this case, the initial format is “yyyy-MM-dd”.
  • The Date object is parsed from the initial string format using the parse method of the SimpleDateFormat object.
  • The code creates a new DateFormat object with the desired date format, which in this case is “dd/MM/yyyy”.
  • The format method of the new DateFormat object is used to format the Date object into a new string with the new date format.
  • Finally, the original and new date strings are printed to the console.

Approach 4: String.format() method

This method is part of the String class and is used to format a string with arguments. You can use this method to format a date into a desired format.

Code:

import java.util.Date;
public class StringFormatExample {
    public static void main(String[] args) {
        // current date in default format
        Date currentDate = new Date();
        System.out.println("Current Date: " + currentDate);     
        // converting to custom format using String.format() method
        String formattedDate = String.format("%1$td-%1$tm-%1$tY", currentDate);
        System.out.println("Formatted Date: " + formattedDate);
    }
}

Output:

Current Date: Tue Mar 02 09:41:42 PST 2023
Formatted Date: 02-03-2023

Explanation of code:

  • The code starts by importing the java.util.Date class, which represents a specific instant in time, with millisecond precision.
  • The StringFormatExample class contains the main method, which is the entry point of the program.
  • Inside the main method, a Date object is created with the current date and time, using the new Date() constructor.
  • The default format for the Date object is printed to the console using the System.out.println method.
  • The String.format method is used to convert the Date object to a custom format. The first argument of the method is a format string, which specifies the order and type of the elements to be formatted.
  • The formatted date is printed to the console using the System.out.println method.

Approach 5: Java 8 Date/Time API

Java 8 introduced a new Date/Time API that provides a better way to handle date and time. It includes classes such as LocalDate, LocalTime, LocalDateTime, and ZonedDateTime, which can be used to format date and time in a desired format.

Code:

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

public class DateTimeExample {
    public static void main(String[] args) {
        // Create LocalDateTime object representing current date and time
        LocalDateTime now = LocalDateTime.now();
               // Define a DateTimeFormatter object with the desired output format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                // Format the LocalDateTime object using the DateTimeFormatter object
        String formattedDate = now.format(formatter);
                // Print the formatted date
        System.out.println("Formatted date: " + formattedDate);
    }
}

Output:

Formatted date: 2023-02-23 15:45:30

Explanation of code:

  • The java.time.LocalDateTime class is used to represent a date and time in the ISO-8601 calendar system, such as 2023-02-23T15:45:30.
  • The java.time.format.DateTimeFormatter class is used to format dates and times into text using patterns of letters and symbols, such as “yyyy-MM-dd HH:mm:ss”.
  • The ofPattern() method of the DateTimeFormatter class is used to create a DateTimeFormatter object with the desired output format.
  • The format() method of the LocalDateTime class is used to format a LocalDateTime object using the DateTimeFormatter object.
  • The formatted date is returned as a String object.
  • The System.out.println() method is used to print the formatted date to the console.

Best Approach for Converting Data Format in Java

The Java 8 Date/Time API is considered to be the best approach for handling date and time operations in Java due to its simplicity, flexibility, and powerful features. There are some reasons why Java 8 Date/Time API can be considered the best approach for converting date format in Java:

  1. It provides a simple and consistent API for handling date and time operations.
  2. It is thread-safe and immutable, which makes it easier to reason about and prevents concurrency issues.
  3. It supports formatting and parsing of date and time objects using the DateTimeFormatter class, which is similar to SimpleDateFormat but more powerful and flexible.
  4. It provides a range of built-in classes for representing different types of date and time objects, including LocalDate, LocalDateTime, ZonedDateTime, Instant, and more.
  5. It supports time zone handling and daylight saving time automatically, which can be a headache to handle manually.
  6. It is backward-compatible with the existing java.util.Date and java.util.Calendar classes, which makes it easier to migrate existing code to the new API.

Sample Problems for Converting Data Format in Java

Sample Problem 1

Assume that you have a list of dates in string format as follows:

List<String> dates = Arrays.asList("2022-05-14 23:45:00", "2023-02-23 09:15:30", "2024-11-10 15:30:45");

You need to convert these dates into a new format of “dd MMMM yyyy hh:mm a”, for example “14 May 2022 11:45 PM”, “23 February 2023 09:15 AM”, “10 November 2024 03:30 PM”.

Write a Java program that uses SimpleDateFormat class to convert these dates into the new format and print the results to the console.

Solution:

  • We start by defining the list of dates in string format as a List<String>.
  • We then create two instances of the SimpleDateFormat class: one for the input format and one for the output format.
  • We use a for loop to iterate through each date in the list.
  • Inside the loop, we use the parse() method of the input SimpleDateFormat instance to convert the string representation of the date into a Date object.
  • We then use the format() method of the output SimpleDateFormat instance to convert the Date object into the desired string format.
  • Finally, we print the new string representation of the date to the console.
  • We also catch any exceptions that may occur during the conversion process and print the stack trace to the console.

Dependencies:

  • java.util.Date: This is a class in Java that represents a specific instant in time with millisecond precision. It is used to store the date and time values before and after conversion.
  • java.text.SimpleDateFormat: This is a class in Java that is used to format and parse dates in a specific format. It is used to define the format of the date and time values before and after conversion.
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class SimpleDateFormatExample {
    public static void main(String[] args) {
        List<String> dates = Arrays.asList("2022-05-14 23:45:00", "2023-02-23 09:15:30", "2024-11-10 15:30:45");
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat outputFormat = new SimpleDateFormat("dd MMMM yyyy hh:mm a");
        for (String dateString : dates) {
            try {
                Date date = inputFormat.parse(dateString);
                String newDateString = outputFormat.format(date);
                System.out.println(newDateString);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Output:

Original Date: Fri Feb 11 14:32:00 IST 2022
Formatted Date (yyyy-MM-dd): 2022-02-11

Sample Problem 2

Write a Java program that takes a date in the format “yyyy/MM/dd” and converts it to the format “dd-MMM-yyyy”. Use the DateTimeFormatter class to perform the conversion.

Solution:

  • The program takes a date in the format “yyyy/MM/dd” as a string input using the variable inputDate.
  • The LocalDate.parse() method is used to parse the input date string into a LocalDate object using the DateTimeFormatter class with the pattern “yyyy/MM/dd”.
  • The LocalDate.format() method is used to format the LocalDate object into a string with the pattern “dd-MMM-yyyy” using the DateTimeFormatter class.
  • The resulting string is stored in the variable outputDate.
  • The input and output dates are printed to the console using the System.out.println() method.

Dependencies:

  • java.time.LocalDate: This is a class in the Java 8 Date/Time API that represents a date without a time zone. It provides methods for manipulating and formatting dates.
  • java.time.format.DateTimeFormatter: This is a class in the Java 8 Date/Time API that provides methods for formatting and parsing dates and times.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample {
    public static void main(String[] args) {
        String inputDate = "2022/02/23";
        LocalDate date = LocalDate.parse(inputDate, DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String outputDate = date.format(DateTimeFormatter.ofPattern("dd-MMM-yyyy"));
        System.out.println("Input Date: " + inputDate);
        System.out.println("Output Date: " + outputDate);
    }
}

Output:

Input Date: 2022/02/23
Output Date: 23-Feb-2022

Sample Problem 3

You are given a CSV file containing the following data:

Name, Date of Birth, Email
John Smith, 02/05/1987, [email protected]
Jane Doe, 12/25/1990, [email protected]
Bob Johnson, 08/15/1985, [email protected]

You need to read this data from the file, convert the date format of the Date of Birth column from “MM/dd/yyyy” to “dd MMM yyyy” format using the DateFormat class, and then write the updated data to a new CSV file.

Solution:

  • We begin by opening the input and output files using the File class, Scanner class, and PrintWriter class.
  • We create two DateFormat objects: inputDateFormat and outputDateFormat. The inputDateFormat is used to parse the date of birth from the input file, and the outputDateFormat is used to format the date of birth in the desired format.
  • We read each line of the input file using the Scanner class, and split each line into an array of parts using the split() method.
  • We parse the date of birth from the input file using the inputDateFormat object, and format it in the desired format using the outputDateFormat object.
  • We write the updated data (name, formatted date of birth, and email) to the output file using the PrintWriter class.
  • Finally, we close the input and output files.

Dependencies:

  • java.io.File: Provides an abstraction for working with files and directories.
  • java.io.IOException: Represents an error that occurs when working with input/output operations, such as reading or writing files.
  • java.io.PrintWriter: A convenience class for writing formatted text to a file.
  • java.text.DateFormat: An abstract class for formatting and parsing dates and times.
  • java.text.ParseException: An exception thrown when a date or time string cannot be parsed using the specified format.
  • java.text.SimpleDateFormat: A concrete subclass of DateFormat that allows formatting and parsing of dates and times in a specified pattern.
  • java.util.Scanner: A class used for reading input from various sources, including files.
import java.io.*;
import java.text.*;
import java.util.*;
public class DateFormatExample {
    public static void main(String[] args) {
        try {
            // Open the input and output files
            File inputFile = new File("input.csv");
            File outputFile = new File("output.csv");
            Scanner scanner = new Scanner(inputFile);
            PrintWriter writer = new PrintWriter(outputFile);
                        // Create a DateFormat object to parse and format dates
            DateFormat inputDateFormat = new SimpleDateFormat("MM/dd/yyyy");
            DateFormat outputDateFormat = new SimpleDateFormat("dd MMM yyyy");
                        // Read and process each line of the input file
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String[] parts = line.split(",");
                                // Parse the date of birth and format it in the desired format
                Date dob = inputDateFormat.parse(parts[1]);
                String formattedDob = outputDateFormat.format(dob);
                                // Write the updated data to the output file
                writer.println(parts[0] + "," + formattedDob + "," + parts[2]);
            }
                        // Close the input and output files
            scanner.close();
            writer.close();
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }
}

Output:

After running the program, the output.csv file will contain the following data:

John Smith,05 Feb 1987,[email protected]
Jane Doe,25 Dec 1990,[email protected]
Bob Johnson,15 Aug 1985,[email protected]

Sample Problem 4

Write a program that takes a date string in the format “yyyy-MM-dd” and converts it to a string in the format “MMM dd, yyyy” using the String.format() method.

Solution:

  • The program takes a date string in the format “yyyy-MM-dd” as input and converts it to a string in the format “MMM dd, yyyy”.
  • The LocalDate class from the java.time package is used to parse the date string to a LocalDate object using the parse() method and ISO_LOCAL_DATE format.
  • The String.format() method is used to format the date using the desired format, where %s is used to format the month abbreviation, %d is used to format the day of the month, and %d is used to format the year.
  • The formatted date string is then printed to the console.

Dependencies:

  • java.time.LocalDate: This class represents a date in the ISO calendar system. It provides methods to parse and format dates.
  • java.time.format.DateTimeFormatter: This class provides methods to format and parse dates using specified patterns.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateFormatExample {
    public static void main(String[] args) {
        // date string in "yyyy-MM-dd" format
        String dateString = "2022-03-01";
                // parse the date string to a LocalDate object using the ISO_LOCAL_DATE format
        LocalDate date = LocalDate.parse(dateString);
                // format the date using the MMM dd, yyyy format and String.format() method
        String formattedDate = String.format("%s %d, %d", date.getMonth(), date.getDayOfMonth(), date.getYear());
        
        // print the formatted date string
        System.out.println("Formatted date: " + formattedDate);
    }
}

Output:

Formatted date: Mar 1, 2022

Sample Problem 5

Write a program that reads a date and time in the format “MM/dd/yyyy HH:mm:ss” from the user and converts it to the format “yyyy-MM-ddTHH:mm:ss” using the Java 8 Date/Time API.

Solution:

  • We import the necessary classes: LocalDateTime from java.time and DateTimeFormatter from java.time.format. We also import Scanner from java.util for reading input from the user.
  • We define a class DateTimeConversion with a main method.
  • Inside the main method, we create a new Scanner object to read input from the user.
  • We prompt the user to enter a date and time in the format “MM/dd/yyyy HH:mm:ss” and read the input string using the nextLine method of the Scanner class.
  • We create a DateTimeFormatter object using the ofPattern method and the pattern “MM/dd/yyyy HH:mm:ss” to specify the format of the input string.
  • We use the parse method of the LocalDateTime class to parse the input string to a LocalDateTime object using the formatter we created in the previous step.
  • We create another DateTimeFormatter object using the ofPattern method and the pattern “yyyy-MM-dd’T’HH:mm:ss” to specify the desired output format.
  • We use the format method of the LocalDateTime class to format the LocalDateTime object to a string using the formatter we created in the previous step.
  • We print the formatted string to the console using the println method of the System.out object.

Dependencies:

  • java.time.LocalDateTime for representing a date and time
  • java.time.format.DateTimeFormatter for parsing and formatting dates and times in various formats
  • java.util.Scanner for reading input from the user
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class DateTimeConversion {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Read the date and time from the user
        System.out.print("Enter the date and time (MM/dd/yyyy HH:mm:ss): ");
        String input = scanner.nextLine();
        // Parse the input string to a LocalDateTime object using a formatter
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(input, inputFormatter);
        // Format the LocalDateTime object to a string using another formatter
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        String output = dateTime.format(outputFormatter);
        // Print the formatted string to the console
        System.out.println(output);
    }
}

Output:

The code will take input from user and display the result

Conclusion

In conclusion, converting date formats is a common task in Java programming, and there are several approaches available to accomplish this task, including SimpleDateFormat, DateTimeFormatter, DateFormat, String.format() method, and Java 8 Date/Time API.

Each approach has its own advantages and disadvantages, and the choice of approach depends on factors such as the complexity of the date format, the performance requirements, and the specific use case.

It is important to understand the dependencies involved in each approach and to choose the one that best suits the requirements of the project.