Home > Java > javaTutorial > body text

How to Parse ISO-8601 DateTime with Colons in Offset Using Java?

Mary-Kate Olsen
Release: 2024-10-31 08:11:29
Original
340 people have browsed it

How to Parse ISO-8601 DateTime with Colons in Offset Using Java?

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
Copy after login

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>
Copy after login

This code snippet accomplishes the following steps:

  1. Creates two SimpleDateFormat objects, one for parsing the input date and time string and the other for formatting the output.
  2. Parses the input date and time string into a Date object.
  3. Reformats the Date object using the output format string.
  4. Outputs the reformatted date and time string.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template