Date format conversion with setLenient()
Why date conversion?
We need to convert the date from one format to another according to our use-cases or sometimes to support the backend APIs.
How to convert dates?
The most commonly used API for date conversion in Kotlin/Java or more specifically in Android is SimpleDateFormat.
To convert date from one format to another we need to do something like this:
The above code will work perfectly and print the expected output as 1998–09–21.
But, Wait!
What if the fromFormat is yyyy-MM-dd or ddMMyyyy rather than dd-MM-yyyy. Ideally, This should not convert the date and throw an ParceException, but that’s not the case. It’ll get converted to some random date which might not even be a valid one.
For instance, below are the two examples with different formats
Improved date conversion
We need to add isLenient = FALSE to strictly follow the given format and if it’s not then .parse() method will throw a ParseException, and then we can identify whether the given date is converted to the expected format correctly or not; JavaDoc
isLenient is set to TRUE by default unless specified.
If you liked the post or it somehow helped in your development process, Don’t forget to 👏 this article. Feel free to give feedback or suggestions.
Connect on LinkedIn