解析日期字符串:一些格式正确的字符串返回错误

时间:2017-07-06 10:46:50

标签: java scala

尝试从字符串中检索星期几时,虽然字符串对应于预定义的格式,但有时会发生错误。

下面是用于解析字符串和格式定义的函数:

val dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
def getDayOfWeek(date: String): Int = {
    val stringToParse = date.substring(0, 19)
    try {
      val now = Calendar.getInstance()
      now.setTime(dateFormat.parse(stringToParse))
      println("Correct time string: " + stringToParse)
      now.get(Calendar.DAY_OF_WEEK)
    } catch {
      case _: Throwable => println("Wrong time string: " + stringToParse)
        -1
    } 
}

以下是成功/未成功解析字符串的示例:

Correct time string: 2017-01-01 04:00:00
Wrong time string: 2017-05-04 15:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-06-13 07:00:00
Correct time string: 2017-05-04 15:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-01-01 04:00:00
Correct time string: 2017-05-04 15:00:00
Correct time string: 2017-06-13 07:00:00
Correct time string: 2017-05-04 15:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-06-13 07:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-06-13 07:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-01-01 05:00:00
Wrong time string: 2017-06-13 07:00:00
Correct time string: 2017-01-01 05:00:00
Correct time string: 2017-05-04 16:00:00
Correct time string: 2017-05-04 16:00:00

有谁知道在上述情况下可能导致错误的原因是什么?我没有发现成功/不成功的例子之间的任何差异。

谢谢!

1 个答案:

答案 0 :(得分:5)

问题是你的SimpleDateFormat是全局声明的。

带上你的行

val dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

在函数内部。

SimpleDateFormat不是线程安全的,我假设您必须从外部非同步代码调用getDayoftheweek()函数。