Date() in worker is reporting Thu Jan 01 1970 00:00:00 GMT+0000

I recently encounter a weird thing in the worker platform. When I try to get current date

let today = new Date();

It returns Jan 01 1970. Is it a bug? Or I am doing something wrong.

Ok, if I declare new Date() under an async function, it will produce today’s date. But not if it’s outside a function.
Why?

Kenton Varda, the architect of Cloudflare Workers, has posted a great explanation on why this happens here

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.

4 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.