Parsing ISO-8601 DateTime with Colons in Offset Using Java
When encountering a date and time string in the ISO-8601 format that includes a colon in the offset, parsing it in Java can prove challenging. Consider the specific case of a date and time string in the following format:
2013-04-03T17:04:39.9430000 03:00
To successfully parse this string and convert it to a more readable format, such as "dd.MM.yyyy HH:mm," we can utilize Java's SimpleDateFormat class.
The following Java code demonstrates how to parse and reformat the date and time string:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Iso8601DateTimeParser {
public static void main(String[] args) {
// Input date string in ISO-8601 format
String dateString = "2013-04-03T17:04:39.9430000 03:00";
// Create SimpleDateFormat objects for input and output formats
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
SimpleDateFormat outFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
try {
// Parse the input date string into a Date object
Date dtIn = inFormat.parse(dateString);
// Reformat the Date object to the desired output format
String dtOut = outFormat.format(dtIn);
// Print the reformatted date string
System.out.println("Reformatted Date: " dtOut);
} catch (ParseException e) {
// Handle parsing exception
System.err.println("Error parsing date string: " e.getMessage());
}
}
}
This code snippet accomplishes the following steps:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3