Date format conversion with setLenient()

Prashant
FloBiz Blog
Published in
2 min readApr 23, 2022

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.

LEFT: Throws ParseException as date provided is not in the expected format. RIGHT: Successfull conversion with isLenient = FALSE as both the formats are same.

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

--

--

Prashant
FloBiz Blog

SDE - II @FloBiz | Ex-Internshala | Mentor @ hackCBS 2.0 | Full Stack Developer | Freelancer | Open-Source Contributer