"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Parse ISO-8601 DateTime with Colons in Offset Using Java?

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

Published on 2024-11-20
Browse:191

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

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:

  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.
Latest tutorial More>

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