Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Date format returns Wrong date intermittently [duplicate]

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 enter image description here

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;
}
like image 272
Deepak Sharma Avatar asked Apr 07 '26 16:04

Deepak Sharma


1 Answers

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?


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!