Most people experience date hell when it’s too late. Although most of these tips would require extensive refactoring or would be useful on greenfield projects only, applying them should increase both testability and maintainability of your application:
- Do not use
Calendaror any other date utility directly. Instead, use dependency to a date provider interface utility injected through IoC to get access to specific dates. That will make your code very testable since you will be able to mock the date provider interface.
- Reduce dependency on
CURDATEor any other utility/function your database may provide to access current datetime values since it reduces the amount of control you have on your data during your tests. Any of these dates should be passed as parameters to the query instead as often as you can. It is really hard to make the database believe the current date is not right now but a different one.
- Define standard date formats from the beginning for your application. These formats will also help you process dates exchanged between layers (i.e. from presentation to business layers) and validate any date field on the client side appropriately. Data format proliferation is a very common issue on enterprise applications and a very difficult one to maintain.
- If you want to use automated timezone/i18n translation please be sure to understand very well what’s going on under the hood. For example, what are the possible timezones for client applications, application servers, and database servers of your system? You will avoid tons of headaches if you take care of this from the beginning. Imagine finding a bug and trying to simulate a different timezone on each layer.
- Use appropriate date/time datatypes for your database columns. What kind or precision (second, millisecond, etc) do you need? Do you need timezone information to be included with the column? It is far easier to test a functionality that handles dates instead that one that handles date/time. It’s all about making things appropriately easy.
Is there any other tip you would like to add? What do you think?