Home >Java >javaTutorial >How to Parse ISO-8601 DateTime with Offset and Colon in Java?

How to Parse ISO-8601 DateTime with Offset and Colon in Java?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 04:45:021047browse

How to Parse ISO-8601 DateTime with Offset and Colon in Java?

Parsing ISO-8601 DateTime with Offset and Colon in Java

Question:

Parsing date time in Java can be challenging when encountering unconventional formats. How can we parse a date time string in ISO-8601 format with an offset and a colon, such as "2013-04-03T17:04:39.9430000 03:00", and convert it to the desired format "dd.MM.yyyy HH:mm"?

Answer:

The specified format is indeed the ISO-8601 standard, which is commonly used in data exchange. To parse and reformat it in Java, we can utilize the SimpleDateFormat class:

<code class="java">import java.text.SimpleDateFormat;
import java.util.Date;

// Example date time string in ISO-8601 format
String isoDateTime = "2013-04-03T17:04:39.9430000+03:00";

// Create SimpleDateFormat objects for input and output formatting
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
SimpleDateFormat outFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");

// Parse the ISO-8601 date time string into a Date object
Date dtIn = inFormat.parse(isoDateTime);

// Convert the Date object to the desired format
String dtOut = outFormat.format(dtIn);

// Output the converted date time in the desired format
System.out.println(dtOut);</code>

In this code:

  • inFormat defines the ISO-8601 parsing format.
  • outFormat defines the desired output format.
  • dtIn stores the parsed Date object.
  • dtOut contains the resulting date time string in the desired format.

The above is the detailed content of How to Parse ISO-8601 DateTime with Offset and Colon in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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