Open In App

How to Convert ISO 8601 Compliant String to java.util.Date?

The ISO 8601 standard provides a convenient way to represent dates and times in a string format that can be easily parsed.

In this article, we will learn how to convert a string in ISO 8601 format to a java.util.Date object.



Conversion of ISO 8601 String to a Date

To convert this ISO 8601 string to a Date, we can use the SimpleDateFormat class. SimpleDateFormat allows us to specify a pattern that matches the format of the string, and then parse the string into a Date.

Note: We will be using the java.text.SimpleDateFormat class to parse the ISO 8601 string into a Date.



Program of converting an ISO 8601 string to a Date in Java

Below is the program for converting an ISO 8601 string to a Date:




// Java program to convert ISO 8601 string to a Date
import java.text.SimpleDateFormat;
import java.util.Date;
  
public class ISO8601Converter 
{
  
    public static void main(String[] args)
    {
  
        // Get today's date as an ISO 8601 string format
        SimpleDateFormat sdf
            = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        String isoDate = sdf.format(new Date());
  
        sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        try {
            // Parse the ISO 8601 string and convert to Date
            Date date = sdf.parse(isoDate);
  
            // Print the converted date
            System.out.println(date);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output
Thu Feb 08 11:21:56 UTC 2024

Explanation of the Program:

In the above program,

Note: Here, by default the timezone is in UTC format, you can also change it according to the need.

Article Tags :