Luniam Luniam -3 years ago 117
Java Question

date time parse is not enforcing the format

I have a string and a format. I want to convert the string to date time using the format. But simple date time format is converting the string to date time even the input string is in a wrong format.

val formatter = new SimpleDateFormat("yyyyMMdd")
val dateInString = "2017042er7"

try {
val date = formatter.parse(dateInString)

} catch {

case e:Exception=>println(e)

How can I enforce the format?

**UPDATE:: ** using joda time formatter solved the issue. You can also use java time formatter(as one of the answers suggested).

Answer Source

You should use the new java.time API and its DateTimeFormatter to parse your dates. it allows for much greater control and correctness and is stricter with the format.

Leave the old java.util.Date, and SimpleDateFormatter behind and just convert to them when you need it to interact with a library.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download