A lot has been written about date and time handling in Mendix. There is no separate date or time type. All our storage involving dates and/or time data is done via a Timestamp, aka Date and Time type. This also brings some challenges, as even though you might just want to store one of them, you always have to deal with both. This could be a struggle when you do this during any ordinary year, month or day. February 29th, however, is a whole different beast. Computers calculate precisely as we instruct them, and a leap year is already a difficult concept for humans. You have a recipe for disaster when you add Mendix’s abstraction to the already challenged Java layer. In this edition of Mendix Ignite, I will explain the do’s and don’ts that have helped me prevent significant disasters during the last 3 leap years.
Don’ts
Let us dive into what you want to avoid first.
Directly calculating with leap day when you pass into the next year could have unforeseen consequences. As long as you are okay with that, nothing is wrong, but it is wise to avoid calculating with February 29th.
Using custom Java date calculations.
Do’s
And now some best practices you do want to apply.
Validate if you are in a leap year by using the following code snippet:
By doing so, you will avoid running into potential issues, or you can trigger some nice defensive code dealing with the issues.
Validate if you are dealing with February 29th with the next code snippet:
This will allow you again to avoid potential issues for the leap day itself. Especially those scenarios described earlier.
To try out some of this for yourself and get you started on leap year/day calculations, I have created a demo project, which you may download by going to the GitHub project page.
Feel free to add your pull requests for additional scenarios and some of your leap-year issues + solutions in the comments.