How to Convert ISO 8601 Compliant String to java.util.Date?
Last Updated :
09 Feb, 2024
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
import java.text.SimpleDateFormat;
import java.util.Date;
public class ISO8601Converter
{
public static void main(String[] args)
{
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 {
Date date = sdf.parse(isoDate);
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,
- It gets today’s date as an ISO 8601 formatted string (yyyy-MM-dd’T’HH:mm:ss).
- Then, it parses this ISO string into a Date object using a SimpleDateFormat with the ISO pattern.
- Then the converted Date is printed.
Note: Here, by default the timezone is in UTC format, you can also change it according to the need.
Share your thoughts in the comments
Please Login to comment...