Pergunta

I am trying to create a Joda DateTime object from the String startTime, then format it and just extract the time out eg H:mm.

I get the following Exception below. Could anyone tell me why?

Thanks in advance Matt

startTime = startTime.trim();

Log.e(TAG, "startTime = " + startTime);

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
DateTime dt = dtf.parseDateTime(startTime);

DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm");
String formattedStart = fmt.print(dt);

Log.e(TAG, "formattedStart = " + formattedStart);

.

05-07 10:22:01.812: E/WebService(10032): startTime = 2014-05-07T08:15:52.747+01:00
05-07 10:22:01.832: E/AndroidRuntime(10032): FATAL EXCEPTION: AsyncTask #3
05-07 10:22:01.832: E/AndroidRuntime(10032): java.lang.RuntimeException: An error occured while executing doInBackground()
05-07 10:22:01.832: E/AndroidRuntime(10032):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
05-07 10:22:01.832: E/AndroidRuntime(10032):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
05-07 10:22:01.832: E/AndroidRuntime(10032):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
05-07 10:22:01.832: E/AndroidRuntime(10032):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
05-07 10:22:01.832: E/AndroidRuntime(10032):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-07 10:22:01.832: E/AndroidRuntime(10032):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
05-07 10:22:01.832: E/AndroidRuntime(10032):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
05-07 10:22:01.832: E/AndroidRuntime(10032):    at java.lang.Thread.run(Thread.java:856)
05-07 10:22:01.832: E/AndroidRuntime(10032): Caused by: java.lang.IllegalArgumentException: Invalid format: "2014-05-07T08:15:52.747+01:00" is malformed at ".747+01:00"
05-07 10:22:01.832: E/AndroidRuntime(10032):    at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:866)
Foi útil?

Solução

If you are working with GMT date, it's better to use the standard ISODateTimeFormat that comes from Joda. For example:

startTime = startTime.trim();

Log.e(TAG, "startTime = " + startTime);

DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
DateTime dt = dtf.parseDateTime(startTime);

DateTimeFormatter fmt = DateTimeFormat.forPattern("HH:mm");
//optional, you can also define locale and zone
//.withLocale(Locale.getDefault())
//.withZone(DateTimeZone.getDefault());
String formattedStart = fmt.print(dt);

Log.e(TAG, "formattedStart = " + formattedStart);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top