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:
<code class="java">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()); } } }</code>
This code snippet accomplishes the following steps:
The above is the detailed content of How to Parse ISO-8601 DateTime with Colons in Offset Using Java?. For more information, please follow other related articles on the PHP Chinese website!