Note that there are some explanatory texts on larger screens.

plurals
  1. POConverting ISO 8601-compliant String to java.util.Date
    text
    copied!<p>I am trying to convert an <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a> formatted String to a <code>java.util.Date</code>. </p> <p>I found the pattern <code>yyyy-MM-dd'T'HH:mm:ssZ</code> to be ISO8601-compliant if used with a Locale (compare sample).</p> <p>However, using the <code>java.text.SimpleDateFormat</code>, I cannot convert the correctly formatted String <code>2010-01-01T12:00:00+01:00</code>. I have to convert it first to <code>2010-01-01T12:00:00+0100</code>, without the colon. </p> <p>So, the current solution is</p> <pre class="lang-java prettyprint-override"><code>SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.GERMANY); String date = "2010-01-01T12:00:00+01:00".replaceAll("\\+0([0-9]){1}\\:00", "+0$100"); System.out.println(ISO8601DATEFORMAT.parse(date)); </code></pre> <p>which obviously isn't that nice. Am I missing something or is there a better solution?</p> <hr> <p><strong>Answer</strong></p> <p>Thanks to JuanZe's comment, I found the <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-Time</a> magic, it is also <a href="http://johannburkard.de/blog/programming/java/date-time-parsing-formatting-joda-time.html" rel="noreferrer">described here</a>.</p> <p>So, the solution is</p> <pre class="lang-java prettyprint-override"><code>DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis(); String jtdate = "2010-01-01T12:00:00+01:00"; System.out.println(parser2.parseDateTime(jtdate)); </code></pre> <p>Or more simply, use the default parser via the constructor:</p> <pre class="lang-java prettyprint-override"><code>DateTime dt = new DateTime( "2010-01-01T12:00:00+01:00" ) ; </code></pre> <p>To me, this is nice.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload