Java的SimpleDateFormat能否返回无效日期?

huangapple go评论61阅读模式
英文:

can java simple date format return an invalid date?

问题

尝试调试一个让我感到困惑的问题。在下面的代码中,是否存在任何情况,它可以返回一个字符串 "20200931"(九月只有30天)。我认为无论如何构造,Java日期都不会保存无效日期,对吗?我在数据库表中看到这个无效日期字符串。这个日期来自对一个SOAP服务的调用,该服务返回一个格式为 "2020-09-01-05:00" 的字符串,然后将其转换为一个 java.util.Date 对象。最后,它使用下面的函数将其转换回字符串并写入我们的数据库表。无论SOAP服务是否返回正确的日期,我都不明白 dateFormat 函数如何返回 "20200931"。

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

...

private static final DateFormat PERIOD_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");

public static String formatDate(Date dt) {
    return dt == null ? "" : PERIOD_DATE_FORMAT.format(dt);
}
英文:

Trying to debug an issue that is baffling me. Is there any scenario where the below code could return a string "20200931" (there are only 30 days in September). I don't think a java date can hold an invalid date no matter how it is constructed correct? I am seeing this invalid date string in a database table. The date is coming from a call to a soap service which returns a string in format "2020-09-01-05:00" and then converts it to a java.util.Date object. Finally it uses the below function to convert back into a string and writes to our database table. Regardless if the soap service returns the correct date or not I dont see how the dateFormat function can return "20200931".

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

...

	private static final DateFormat PERIOD_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");

    public static String formatDate(Date dt) {
        return dt == null? "" : PERIOD_DATE_FORMAT.format(dt) ;
    }

答案1

得分: 1

感谢所有的评论。

  1. 我没有编写这段代码 - 它非常旧。
  2. 这是一个生产问题,尝试调试的不是我们正在编写的新代码。
  3. 我们存储的不是单一日期,而是一系列用下划线分隔的日期,并在其他系统中用于查找,因此它是一个字符串。
  4. 我知道数据库中有日期对象。

我们发现的问题是 SimpleDateFormat 不是线程安全的,当从不同线程中重复调用时会生成错误的日期字符串。解决方案是去除 static 关键字,这样每个实例都会有自己的日期格式对象。

英文:

Thanks for all the comments.

  1. I didn't write this code - its very old.
  2. Its a production issue trying to debug not new code we are writing.
  3. Its not a date we are storing but a series of dates separated with _ and used in other systems for lookups hence its a string.
  4. I know there are date objects in database.

The issue we found is that SimpleDateFormat is not thread safe and it is generating bad date strings when called repeatedly from different threads. The solution is to remove the static keyword so each instance gets its own date format object.

huangapple
  • 本文由 发表于 2020年9月24日 04:07:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64035505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定