CodeSOD: A Double Date

This post was originally published on this site

The Daily WTF

Alice picked up a ticket about a broken date calculation in a React application, and dropped into the code to take a look. There, she found this:

export function calcYears(date) { return date && Math.floor((new Date() – new Date(date).getTime()) / 3.15576e10) }

She stared at it for awhile, trying to understand what the hell this was doing, and why it was dividing by three billion. Also, why there was a && in there. But after staring at it for a few minutes, the sick logic of the code makes sense. getTime returns a timestamp in milliseconds. 3.15576e10 is the number of milliseconds in a year. So the Math.floor() expression just gets the difference between two dates as a number of years. The && is just a coalescing operator- the last truthy value gets returned, so if for some reason we can’t calculate the number of years (because of bad

To read the full article click on the 'post' link at the top.