Some programming languages really encourage using UNIX timestamps for working with dates. PHP is a good example of such a language. Functions like date, strtotime, strftime are used all the time. Most people don’t realize that timestamps in general can’t really be used for calculations though. The problem is that most countries use daylight saving time, which means that two times a year the local timezone changes. This nicely breaks the assumption that every day has 24 hours. It doesn’t. Sometimes it has 23 or 25 hours.
This StackOverflow answer is a nice example of the problem:
$mondayStr = "last monday";
if (date('N') !== '1') { // it's not Monday today
$mondayStr .= " last week";
}
$monday = strtotime($mondayStr);
echo date('r', $monday); // Mon, 22 Feb 2010 00:00:00 +1000
$sunday = $monday + 86400 * 7 - 1;
echo date('r', $sunday); // Sun, 28 Feb 2010 23:59:59 +1000
The code seems logical. Get the timestamp of the last Monday, add 60 * 60 * 24 * 7 – 1 seconds and you have the end of Sunday. Works fine most of the time. Although, if the $monday happens to be Mon, 22 Mar 2010 00:00:00, the date that was supposed to be Sun, 28 Mar 2010 23:59:59 will actually be Mon, 29 Mar 2010 00:59:59. Why? Because 28 March 2010 has only 23 hours.
Never use timestamps to do calendar calculations. It’s hard to get it right. If you really have to, at least use GMT timestamps.
To be honest, I don’t read technical books much. I prefer reading the official documentation for a product I need to work with, or use some other ways to get information about it. I always assumed people who write such books are experts though. There are many book authors on Stack Overflow, but today I encountered a particularly interesting situation with one of them.
Somebody asked a question about a Perl module a few days ago and based on reading the source code of the module, I gave them one possible way to solve the problem. Today, an author of multiple Perl books came in and very confidently claimed that my solution will never work. I explained him why he is wrong, but it didn’t help. The problem was that he failed to read the source code correctly and made incorrect assumptions based on that. I pointed him to specific parts of the code, still nothing. At that point I wanted to gave up, but later he came up with a broken example, which didn’t work for different reasons, that should show me why I’m wrong. Soon after that he realized what is wrong about the example, changed his answer and deleted all his old comments, as if they never happened.
The problem I see is not this specific case (I’ve seen far more of them, either on Stack Overflow or some IRC channels), but the fact that even average programmers write popular programming books. And people learn from these books. I guess the saying about teachers who failed to apply their knowledge in practice, which I can’t remember right now, applies even for book authors. What a wonderful world.
(I just needed to get this out of myself.)