I have a String, 2013-10-07T23:59:51.205-07:00
, want to convert this to Java date object. I am getting parsing error.
date = new SimpleDateForma
The problem is that -07:00
is not a valid Time zone . The Time Zone should have this format, for example something like -0800
.
Your pattern is wrong, you should use the following:
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
.parse("2013-10-07T23:59:51.205-07:00");
The 'X' indicates the Time zone in the ISO 8601 format as expressed in your String
here: '.205-07:00'
For more information read the doc: SimpleDateFormat
try
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.parse("2013-10-07T23:59:51.205-0700");
The Z is not a literal and the timezone does not have a colon
See the examples at http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
If java7 is being used then Z
can be replaced with X
and the timezone can have a colon
You should use XXX
for the format -07:00
, instead of Z
and X
.
Date sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
.parse("2013-10-07T23:59:51.205-07:00");
Look at the example of this docs.
Z
shouldn't be inside quotes. I don't think Z
would work for your given timezone. Before Java 7, I guess there wasn't any format to parse ISO 8601 format timezone with colon in between. You should use -0700
instead.
However, from Java 7 onwards, you have an option for parsing ISO 8601 format timezone using X
instead of Z
. See javadoc for SimpleDateFormat. Just use the following format:
// This would work from Java 7 onwards
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
.parse("2013-10-07T23:59:51.205-07:00");
Use this trick to parse ISO8601 datetime format. I admit have not tried this with millisecond part within a string value maybe it gives you an extra headache. This works for Java6.
import javax.xml.bind.DatatypeConverter;
Calendar cal = DatatypeConverter.parseDateTime(strDatetime);
If am remembering correct cal instance may not use a system-default timezone. Its initialized to the origin string value timezone. If you want instance to use system timezone you can do this conversion.
long ts = cal.getTimeInMillis();
cal = Calendar.getInstance();
cal.setTimeInMillis(ts);