https://kotlinlang.org logo
i

iex

04/07/2020, 11:28 AM
Hi everyone! How do I make
java.text.SimpleDateFormat
 fail if the date string doesn't match exactly? Tried setting
isLenient
to false but it didn't work. Specifically I want that if the format is "yyyy-MM-dd", e.g. "2019-08-05T235959+0200" is NOT parsed. it should only parse if the date string is "2019-08-05"
Copy code
val str = "2019-08-05T23:59:59+0200"
val format = SimpleDateFormat("yyyy-MM-dd")
format.isLenient = false
format.parse(str) // should return null or crash
d

df

04/07/2020, 11:41 AM
In your case LocalDate.parse() should be sufficient
d

diesieben07

04/07/2020, 11:41 AM
Any reason you are not using
DateTimeFormatter
from
java.time
?
For
SimpleDateFormat
you can use
ParsePosition
to detect extraneous text at the end:
Copy code
val position = ParsePosition(0)
val input = "2019-08-05T23:59:59+0200"
val parsed = format.parse(input, position)
if (position.index != input.length) {
    throw Exception("Invalid Date")
}
i

iex

04/07/2020, 2:09 PM
I'm not using
java.time
because I'm using the Android SDK
Not sure about
LocalDate.parse()
? Haven't seen this
d

diesieben07

04/07/2020, 2:09 PM
LocalDate
is also part of
java.time
.
i

iex

04/07/2020, 2:10 PM
ParsePosition
seems usable 👍
ah, okay. Then I can't use
LocalDate
either
thx
d

diesieben07

04/07/2020, 2:10 PM
But not sure if its possible for you to use that. But if at all possible you should avoid the pre
java.time
Time apis like the plague
They are ridiculously hard to use correctly.
i

iex

04/08/2020, 9:52 PM
ah good to know, thanks!
2 Views