-1

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?

Regexident
  • 29,441
  • 10
  • 93
  • 100
Envin
  • 1,463
  • 8
  • 32
  • 69
  • 6
    In future, if you've tried things it's worth showing what you've tried and explaining how it's not worked for you. – Jon Skeet May 10 '13 at 20:30
  • FYI, this format with minimal use of separators is known as the [“basic” version of the ISO 8601 standard formats](https://en.wikipedia.org/wiki/ISO_8601#General_principles). The “extended” format uses separators such as `2013-05-10T20:21:32Z `. – Basil Bourque Oct 12 '16 at 03:48

2 Answers2

9

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);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

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.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154