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!
Throwableis generally not advisable. You may want to look into theNonFatalextractor, documented here: scala-lang.org/api/2.11.8/…