简体   繁体   中英

Converting an ISO8601 string into DateTime format?

I have a string 20130510T202132Z that I want to convert into a DateTime object.

I've been trying to use Joda to get this to work but I can't get it to work. I've hit every link I can find on the subject -- and used formatters but it simply isn't working out.

What is the best way to do this?

Joda Time makes this really easy, as it has built-in support for the ISO format:

DateTimeFormatter iso = ISODateTimeFormat.basicDateTimeNoMillis();
DateTime dateTime = iso.parseDateTime(text);

The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

DateTimeFormatter

Unfortunately this “basic” (minimal separators) version of the standard ISO 8601 format is not predefined in java.time as of Java 8. Use DateTimeFormatter class to specify a matching pattern.

String input = "20130510T202132Z";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uuuuMMdd'T'HHmmssX" );

By the way, the version with separators such as 2013-05-10T20:21:32Z is known as the extended version of ISO 8601 .

OffsetDateTime

Parse as a OffsetDateTime object. This class represents a moment on the timeline adjusted to a certain offset-from-UTC , resolving to nanoseconds. In this case the offset is UTC itself.

OffsetDateTime odt = OffsetDateTime.parse ( input , f );

odt.toString(): 2013-05-10T20:21:32Z


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , .Calendar , & java.text.SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to java.time.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport .
  • Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM