title: Convert ISO 8601 Date to a Standard String Format
body: <p>I am trying to convert a valid <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="nofollow noreferrer">ISO 8601</a> string to a consistent format so that sort and search using simple lexicographical order is possible.</p>
  
  <p>My application could receive a date/time in any of the following formats, for example:</p>
  
  <pre><code>2015-02-05T02:05:17.000+00:00
  2015-02-05T02:05:17+00:00
  2015-02-05T02:05:17Z
  </code></pre>
  
  <p>These all represent the same date/time and I would like to convert them all to a canonical form for storage, say:</p>
  
  <pre><code>2015-02-05T02:05:17.000Z
  </code></pre>
  
  <p>My first thought was to just parse them using a technique from <a href="https://stackoverflow.com/questions/2201925/converting-iso-8601-compliant-string-to-java-util-date">Converting ISO 8601-compliant String to java.util.Date</a>, and then convert back to the desired string, but this breaks down when dealing with less precise date/times, for example:</p>
  
  <pre><code>2015-02-05T02:05:17Z
  2015-02-05T02:05Z
  2015-02-05Z
  2015-02Z
  2015Z
  </code></pre>
  
  <p>The imprecision of these times should be preserved. They should not be converted to:</p>
  
  <pre><code>2015-02-05T00:00:00.000Z
  </code></pre>
  
  <p>I've looked Java 8 and Joda-Time, but they seem to want to treat everything as specific points in time, and can't model the imprecise nature or partial dates/times.</p>
  
  <p>UPDATE:</p>
  
  <p>Using Java 8, I can do:</p>
  
  <pre><code>OffsetDateTime dateTime = OffsetDateTime.parse("2015-02-05T02:05:17+00:00");
  System.out.println(dateTime.toString());
  </code></pre>
  
  <p>which gives me:</p>
  
  <pre><code>2015-02-05T02:05:17Z
  </code></pre>
  
  <p>which is what I want, but:</p>
  
  <pre><code>OffsetDateTime dateTime = OffsetDateTime.parse("2015-02-05T02:05:17.000+00:00");
  System.out.println(dateTime.toString());
  </code></pre>
  
  <p>also gives me:</p>
  
  <pre><code>2015-02-05T02:05:17Z
  </code></pre>
  
  <p>Notice that java has thrown away the millisecond precision. Specifying 000 is treated the same as not specifying anything, which doesn't seem quite right. </p>