I have a string in standard ISO 8601 format that contains the date/time returned from a web service like so:
String dtStart = "2010-10-15T09:27:37Z"
How do I get this into an object such as Time or Date? I initially want to output it in a different format, but will need to do other stuff with it later (i.e. maybe use in a different format).
Cheers
ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).
The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .
The Date/Time API in Java works with the ISO 8601 format by default, which is (yyyy-MM-dd) . All Dates by default follow this format, and all Strings that are converted must follow it if you're using the default formatter.
String dtStart = "2010-10-15T09:27:37Z"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); try { Date date = format.parse(dtStart); System.out.println(date); } catch (ParseException e) { e.printStackTrace(); }
This is what you are looking for. There is existing post about this problem.
This question was asked in 2010, and back then it was correct that either SimpleDateFormat
or Joda-Time would be the tools you should use. It’s quite a while ago now. Today use
Instant iStart = Instant.parse(dtStart);
Yes, it’s this simple. Your string is in ISO 8601 format, and the classes from java.time
, the modern Java date and time API, parse ISO 8601 without any explicit formatter. Instant
is just one of those classes.
Yes, java.time
works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With