Date time operations is one of those topics that are ubiquitous in programming but do not receive a lot of attention. It is somehow expected that humans intuitvely understand time since we deal with it so often in everyday life. As a result, many developers make silly mistakes when working with date time. In this blog post, we will look at some of these mistakes specifically when parsing/formatting date time.
Sorted by frequency of occurrence from least common to most common (and subtle).
A: Month vs minute
Lowercase “mm” stands for a minute in an hour, but uppercase “MM” stands for the month in a year. It is easy to mix them up.
B: Now wait just a second
Lowercase “s” is for seconds but uppercase “S” is for milliseconds which is used much less often.
C: What day is it? Well it's the 42nd of February of course.
Lowercase “dd” stands for day of the month, but uppercase “DD” stands for day of the year. Although there are valid use-cases for the latter the lowercase version is used much more often.
D: It is 17 PM o'clock
Lowercase "a" is used to denote AM or PM. It should only be used in combination with lowercase "h" which is in the range 1-12. Using "a" in combination with the uppercase "H" makes little sense.
formatDateTime($DateTime, 'HH:mm a')
E: Fun with hours
Uppercase “H” is in the range 0-23, while “h” is in the range 1-12. On the other hand, “K” is in the range 0-11 but “k” is in the range “1-24”, which is non-standard and should be avoided.
Lowercase “h” is usually used singly (rather than requiring exactly two digits), and always in conjunction with an AM/PM specifier – as otherwise, it’s ambiguous. “H” is usually used as “HH”, so that 5 am is represented as “05” for example.
F: Who are you calling week?
This one is by far my favorite. Unlike all other errors on this list which are fairly easy to detect with a few tests, this one is almost impossible to detect. That’s because, for most dates, week year (uppercase "Y") and year (lowercase "y") give the same result. To catch this bug testers need to write cases for the last week of the year for the specific years where the value of y and Y are not the same. I will not even try to explain the reason behind this. If you want to learn more check this link.
formatDateTime(dateTime(1987,12,31)', 'dd MMM YYYY') → results in "31 Dec 1988" 🤯🤯🤯
I hope you enjoyed reading this post and that it helps you make less mistakes in the future!
Automatic code reviewer for Mendix
The automatic code reviewer for Mendix checks for over 100 rules in different categories such as security, performance, and maintainability. There are also around 40 reliability rules whose goal is to find bugs in your app such as the ones above.
Don't wait, sign up for free and experience the power of automated code reviews first hand: https://content.mansystems.com/acr-trial-request. No credit card required.