Skip to main content

Have a single definition of “now”

I’ve been doing a bunch of datetime debugging recently, and this function has been a great help:

function today() {
  return new Date();

It’s not very sophisticated – it just returns the current time – but we use it everywhere we need to get the current time. (You could criticise the name, but at this point we’re all used to it.)

Having a single source of “now” is super helpful for debugging tricky time-specific bugs.

For example, there have been several bugs which only occur on the last day of exhibitions – which are always Sundays. These issues get reported on the day, but disappear by the Monday morning because the exhibition is closed.

By overriding the return value of this function, I can see how the site behaved on the Sunday – and then I can see what went wrong. I can also override the return value in tests, so I can write regression tests to guard against bugs that only occur at specific times.

Having a single definition of “now” is much nicer than having dozens of calls to new Date() scattered through the codebase. If I had to override those calls individually, I might see weird behaviour when different functions had an inconsistent idea of when “now” is.

A real example: we have a function that filters a list of events for ones that are happening in the future. Another function takes a future event, and formats a human-readable description of when the event will occur (“later today”, “tomorrow”, “next week”). If the two functions disagree on when “now” is, the second function could be passed an event it thinks is already in the past. That should never happen in real world use, but it could cause strange behaviour while debugging, and that would slow me down.

Having a single definition of “now” has saved me so much time while debugging. I think I’ve used it to reproduce at least a dozen bugs, and it appears in twice as many tests. If you have to do a lot of tricky datetime logic, I really recommend it.