Reputation: 66565
While trying to retrieve day of the week from the string, sometimes an error occurs although the string corresponds to the predefined format.
Below is the function that is used to parse strings and format definition:
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
}
}
Below are the examples of successfully/unsuccessfully parsed strings:
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
Does anyone know what could cause the error in the above cases? I don't spot any differences between the successful/unsuccessful examples.
Thanks!
Upvotes: 0
Views: 58
Reputation: 456
Problem is your SimpleDateFormat is declared globally.
Bring your line
val dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
inside the function.
SimpleDateFormat is not thread safe, and I assume you must be calling getDayoftheweek() function from outside non-synchronized code.
Upvotes: 5