Hi everyone! How do I make `java.text.SimpleDateFo...
# announcements
i
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
In your case LocalDate.parse() should be sufficient
d
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
I'm not using
java.time
because I'm using the Android SDK
Not sure about
LocalDate.parse()
? Haven't seen this
d
LocalDate
is also part of
java.time
.
i
ParsePosition
seems usable 👍
ah, okay. Then I can't use
LocalDate
either
thx
d
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
ah good to know, thanks!