3 ms·
Anyone who's been programming for more than a year knows, or should know, that you don't do time arithmetic directly on the date representation. You convert ti
by ScottBurson 15y ago
Anyone who's been programming for more than a year knows, or should know, that you don't do time arithmetic directly on the date representation. You convert times to some form that is easy to do arithmetic on, like seconds from 1970-1-1 00:00:00 UTC (the Unix epoch) or 1900-1-1 00:00:00 UTC (the Common Lisp epoch), do all your arithmetic on that, then convert back.
So to add a year, all you have to do is add 365.25 * 24 * 60 * 60.
This was a stunningly stupid, n00b mistake.
- biot 15y agoDon't do that either. December 31, 2012 at 9:00 PM + 365.25 * 24 * 60 * 60 seconds = January 1, 2014 at 3:00 AM. I doubt many people would consider that to be one year later. Let a well-tested library handle the date calculations as you likely haven't thought enough about leap years, leap seconds, daylight savings, historical changes in daylight savings, and so on.
- joe_the_user 15y agoYes, Among all the tasks and problems that seem simple, you'll find Time and date questions to be some of the trickiest. Deriding "noobs" doesn't do anyone any credit.
- sad_panda 15y agoYou're usually pretty safe if you allow well-tested date and time libraries to do all of the heavy lifting.
- ScottBurson 15y agoI'm keenly aware of the complications. My point is that every other professional programmer should be too. I stand by my statement: this was a stunningly stupid, n00b mistake. If I had made it, I would say exactly the same thing.
- ScottBurson 15y agoLet a well-tested library handle the date calculations Yes, that's my point exactly. The conversion from the familiar representation to linear seconds incorporates all of those complications (except leap seconds, which hardly anyone bothers with). If you don't want to use 365.25, you can write code to figure out whether to use 365 or 366; but in neither case will you have a bug like the one Azure hit where a completely invalid date was generated.