Simple Date format returns Wrong date intermittently [duplicate]

心已入冬 提交于 2019-12-17 17:15:31

问题


I am converting Date to string format in yyyy-MM-dd HH:mm:ss format to save in sqlite database below is object declared for simple date format

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

Sometime it prepends pair of zeros in date as you can see in below image

Example Wrong date returns as as below

2018-08-25 02:32:0000

2018-08-25 02:32:0049

2018-0008-25 02:32:50

2018-08-24 0023:32:50

2018-08-0024 23:32:50

I have created custom funtion to correct this wrong date. But I want to know exact cause of this issue.

below is the code

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

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

回答1:


I'm sure that if you don't use that static instance of SimpleDateFormat you will have no problem:

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

See these links:
Why is Java's SimpleDateFormat not thread-safe?
"Java DateFormat is not threadsafe" what does this leads to?




回答2:


SimpleDateFormat is not thread safe that's why you should check if in your calling code there is no issue with that.



来源:https://stackoverflow.com/questions/52000493/simple-date-format-returns-wrong-date-intermittently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!