1
votes

I'm trying to write something that will take in a string with the below format in UTC time and format it to the local time zone grabbed from the phone. However, despite looking at SimpleDateFormat documentation, I'm running across the error that my sample string is unparseable:

W/System.err﹕ java.text.ParseException: Unparseable date: "2014-07-16T21:00:00:000+0000" (at offset 19)
W/System.err﹕ at java.text.DateFormat.parse(DateFormat.java:555)
[...]
D/Set time:﹕ Wed Jul 16 15:10:03 PDT 2014
D/TimeInMilli:﹕ 1405548603565

Code:

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone(); //Get phone's PST zone

String UTCinput = "2014-07-16T21:00:00:000+0000"; //2:00PM PST
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
format.setTimeZone(tz);

Date dateCal = new Date();

try {
    dateCal = format.parse(UTCinput);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

cal.setTime(dateCal);
Log.d("Set time: ", String.valueOf(dateCal));
Log.d("TimeInMilli: ", String.valueOf(cal.getTimeInMillis()));

What is the issue with the way I'm parsing?

1
When running into this kind of mystery, copy-paste example code. StackOverflow.com abounds with examples of SimpleDateFormat code you could have tried before posting.Basil Bourque
Tip: Use either Joda-Time or java.time libraries rather than java.util.Date & SimpleDateFormat which are notoriously troublesome. You can pass your ISO 8601 compliant string directly without need for formatting/converting. DateTime dateTime = new DateTime( "2014-07-16T21:00:00:000+0000" );Basil Bourque

1 Answers

6
votes

Your input String needs to match your DateFormat pattern

String UTCinput = "2014-07-16T21:00:00.000+0000"; //2:00PM PST
                                      ^--- was ":"