简单日期格式 returns 间歇性错误日期

Simple Date format returns Wrong date intermittently

我正在将日期转换为 yyyy-MM-dd HH:mm:ss 格式的字符串格式以保存在 sqlite 数据库中 下面是为简单日期格式声明的对象

public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

有时它会在日期中添加一对零,如下图所示

示例错误日期returns如下

2018-08-2502:32:0000

2018-08-2502:32:0049

2018-0008-2502:32:50

2018-08-240023:32:50

2018-08-0024 23:32:50

我已经创建了自定义函数来更正这个错误的日期。但我想知道这个问题的确切原因。

下面是代码

public static String getCurrentDateTime() {
    Date d = new Date();

    String datetime = sdf.format(d);
    if (datetime.length() > 19) {
        datetime = correctDate(datetime);
    }
    return datetime;
}

SimpleDateFormat 不是线程安全的,这就是为什么你应该检查你的调用代码是否没有问题。

我敢肯定,如果您不使用 SimpleDateFormatstatic 实例,您将不会有任何问题:

public static String getCurrentDateTime() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date d = new Date();
    String datetime = sdf.format(d);
    return datetime;
}

查看这些链接:
Why is Java's SimpleDateFormat not thread-safe?
"Java DateFormat is not threadsafe" what does this leads to?