简单日期格式间歇性地返回错误日期 [英] Simple Date format returns Wrong date intermittently

查看:121
本文介绍了简单日期格式间歇性地返回错误日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:0000

2018-08-25 02:32:0049

2018-08-25 02:32:0049

2018-0008-25 02:32:50

2018-0008-25 02:32:50

2018-08-24 0023:32:50

2018-08-24 0023:32:50

2018-08-0024 23: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.

下面是代码

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

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


推荐答案

我确定如果你没有使用那个静态 SimpleDateFormat 的实例你没有问题:

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

请参阅以下链接:

为什么Java的SimpleDateFormat不是线程安全的?

< a href =https://stackoverflow.com/questions/4021151/java-dateformat-is-not-threadsafe-what-does-this-leads-to>Java DateFormat不是线程安全的这会导致什么?

这篇关于简单日期格式间歇性地返回错误日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆