3

我有一个日期解析问题。在我的应用程序中,我从我们的服务器检索新评论。检索到的纪元长时间戳是正确的,但是当我尝试将它们保存到 sqlite db 时,有时最后的评论会解析错误的日期。

简单日期格式:

this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
this.dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 

解析:

Log.v("GET COMMENT TIME A", ""+cu.getString(cu.getColumnIndex("creation_time")));
try {
    Log.v("GET COMMENT TIME B",""+dateFormat.parse(cu.getString(cu.getColumnIndex("creation_time"))));
    c.setCreation_time(dateFormat.parse(cu.getString(cu.getColumnIndex("creation_time"))));
    Log.v("GET COMMENT TIME C", ""+c.getCreation_time());
} catch (ParseException e) {}

Logcat:以前的评论解析好

01-13 13:01:58.009: V/GET COMMENT TIME A(10536): 2013-01-13 12:01:37
01-13 13:01:58.017: V/GET COMMENT TIME B(10536): Sun Jan 13 13:01:37 CET 2013
01-13 13:01:58.017: V/GET COMMENT TIME C(10536): Sun Jan 13 13:01:37 CET 2013

Logcat:最后一条评论解析错误:

01-13 13:01:58.064: V/GET COMMENT TIME A(10536): 2013-01-13 12:01:41
01-13 13:01:58.064: V/GET COMMENT TIME B(10536): Sun Jan 13 13:01:41 CET 2013
01-13 13:01:58.064: V/GET COMMENT TIME C(10536): Tue Jan 01 13:01:41 CET 2013

因此,当您查看 logcat GET COMMENT TIME B 和 C 时,您可以看到

dateFormat.parse(cu.getString(cu.getColumnIndex("creation_time")))

首先返回一个更正的解析时间,然后再返回 1 行它解析另一个错误的时间?或者为什么 getCreation_time() 有时会返回错误解析的日期?

编辑:评论只有getter和setter

public Date getCreation_time() {
    return creation_time;
}

public void setCreation_time(Date creationTime) {
    this.creation_time = creationTime;
}
4

1 回答 1

3

那么,解析 2 次完全相同的String结果有时会产生不同的结果?我能想到的唯一原因SimpleDateFormat 是不是线程安全的。
经常吗?如果您使用变量而不是实例字段会发生什么?

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 
Log.v("GET COMMENT TIME A", ""+cu.getString(cu.getColumnIndex("creation_time")));
try {
    Log.v("GET COMMENT TIME B",""+dateFormat.parse(cu.getString(cu.getColumnIndex("creation_time"))));
    c.setCreation_time(dateFormat.parse(cu.getString(cu.getColumnIndex("creation_time"))));
    Log.v("GET COMMENT TIME C", ""+c.getCreation_time());
} catch (ParseException e) {}
于 2013-01-16T15:24:12.463 回答