Thursday, January 10, 2008

EDSK ... not to save dates (and/or times) as strings based on formats which can change

Every developer should know not to save dates (and/or times) as strings based on formats which can change.

Such settings will, at some point, change or vary. And when they do: at best, a date may be displayed incorrectly or inconsistently; at worst, the program will crash as it is unable to correctly convert a date.

Why is this important?

Not doing this and trying to deal with varying formats can lead to:
  • regionalisation issues.
  • compatibility issues.
  • unnecessarily complicated programs.

When saving a date and/or time as a string you should use an ISO defined format.

By always using one of these format you will never have to deal with multiple format conversions within a system.

If dates (and or times) are saved as strings in other formats a separate piece of information must also be saved which explains the format. '01/02/2008' could be the first of February or the second of February. '02/03/02' could be an even larger number of possibilities.

Of course, you'd never consider using a two figure year value though. would you?

These formats also have a number of other benefits.
  • They ensure readability and accuracy amongst all systems.
  • They allow for easy sorting and comparison of dates.
  • They are language independent.
  • Most notations are short.
  • They are of a consistent length.

It might be tempting to think that, as computers process dates and times as numbers, this is how you should store them also, when saving to a file or database. The potential downside to this is that you really also need to store the date (and time) from which to start counting also. This means that two pieces of information should be stored. In practice, it is unlikely that anyone would store two pieces of information for each date being recorded by a system. If this was recorded it would likely be in a global setting, or, more likely, in the documentation somewhere. Either way these are likely to be places which are overlooked when they are most needed.

What do you do once you know this?

Don't do it!

Save dates and times using the numeric representations defined in ISO 8601:2004. Such as:


In doing this you can have a simple set of utility functions to convert dates to strings and numerous future headaches are saved.

You can then just worry about formatting dates when they are displayed to the user. Which should be in the user defined format, of course.

What do you think?
Is this something every developer should know? Have you say in the comments.

1 comment: