将String解析为Joda DateTime时出现IllegalArgumentException

时间:2014-05-07 09:26:26

标签: android datetime jodatime

我正在尝试从String startTime创建一个Joda DateTime对象,然后对其进行格式化并只提取时间,例如H:mm。

我在下面得到以下例外情况。谁能告诉我为什么?

先谢谢马特

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)

1 个答案:

答案 0 :(得分:1)

如果您正在使用GMT日期,最好使用来自Joda的标准ISODateTimeFormat。例如:

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);