首页 > 解决方案 > SimpleDateFormat 解析不适​​用于数据库中 UTC 格式的日期

问题描述

我使用 Parse.com,每个 ParseObject 都有日期类型为 UTC 格式的日期列。

我想按日期对从查询中获得的那些对象进行排序。所以我使用 SimpleDateFormat 和 Comparator 来比较日期,但它抛出了这个异常:

java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766) 
     Caused by: java.text.ParseException: Unparseable date: "Thu Dec 06 16:20:00 GMT+01:00 2018" (at offset 0)

代码:

private fun formatQueryData(unsortedList: ArrayList<ParseObject>){
        unsortedList.sortWith(object : Comparator<ParseObject>{
            var f = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'")
            override fun compare(o1: ParseObject, o2: ParseObject): Int {
                try {
                    return f.parse(o1.getDate("date").toString()).compareTo(f.parse(o2.getDate("date).toString()))
                } catch (e: ParseException) {
                    throw IllegalArgumentException(e)
                }
            }
        })
    }

标签: androidsimpledateformatdatetime-parsingandroid-dateparseexception

解决方案


推荐阅读