5

The usual Date object on Cloudflare's workers, all return 1 jan,1970...

What is the proper way to get the current datetime in a workers' code?

Thanks,

G

wanted
  • 309
  • 2
  • 11

1 Answers1

15

The Date object only returns 1970-01-01 when executed at the global scope. If you use it during the event handler for a request, it will correctly return the current date.

let globalDate = Date.now();  // always zero

addEventListener("fetch", event => {
  let localDate = Date.now();  // will return actual current date
})

Background

The reason for this is that Cloudflare Workers runs the global scope at an unspecified time. It might be on-demand when a request arrives, but it could be earlier. In theory, Workers could even execute the global scope only once ever, and then snapshot the state and start from the snapshot when executing on the edge. In order to ensure that such different implementation options do not affect the behavior of deployed workers, the Workers Runtime must ensure that the global scope's execution is completely deterministic. Among other things, that means Date.now() must always return the same value -- zero -- when executed at the global scope.

Kenton Varda
  • 31,348
  • 6
  • 88
  • 84
  • Here is some more info on it: https://community.cloudflare.com/t/cloudflare-workers-how-do-i-measure-execution-time-of-my-method/69672/3 – grabantot Mar 04 '21 at 09:42