Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current date in a Cloudflare's worker

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

like image 641
wanted Avatar asked Oct 21 '19 17:10

wanted


People also ask

How long can Cloudflare workers run?

​​ CPU runtime A Worker may consume up to 10 milliseconds on the Free plan. A Worker or Scheduled Worker may consume up to 50 milliseconds with the Bundled usage model on the Paid Plan. A Worker may consume up to 30 seconds with the Unbound usage model on the Paid Plan.

What can Cloudflare workers do?

Cloudflare Workers are a platform for enabling serverless functions to run as close as possible to the end user. In essence, the serverless code itself is 'cached' on the network, and runs when it receives the right type of request.

How do I run Cloudflare worker locally?

Getting started with local development As mentioned in the introduction, Miniflare 2.0 is now integrated into wrangler 2.0, so you just need to run npx wrangler@beta dev --local to start a fully-local Worker development server or npx wrangler@beta pages dev to start a Cloudflare Pages Functions server.


1 Answers

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.

like image 70
Kenton Varda Avatar answered Sep 22 '22 15:09

Kenton Varda