workers icon indicating copy to clipboard operation
workers copied to clipboard

Unable to get accurate date/time

Open Airyzz opened this issue 2 years ago • 3 comments

When getting the current time with time.Now() we get back incorrect time. I assume this is because tinygo isn't accessing the system clock properly.

Could it be possible to have some function which gets the date and time from the JavaScript side of things?

Airyzz avatar Jul 31 '23 22:07 Airyzz

@Airyzz Thank you for feedback. And I'm sorry about very late response.

I've created 2 examples.

  • go-date-example
    • https://github.com/syumai/workers-playground/tree/main/go-date-example
  • tinygo-date-example
    • https://github.com/syumai/workers-playground/tree/main/tinygo-date-example

Each example outputs result of time.Now().

And I've confirmed that the time in local development with tinygo was the only broken case. Is it about this case that you intend in this report?


The results of these examples are below.

local result

# go-date-example
$ curl http://localhost:8787/now
2024-01-01 23:44:54.185 +0900 UTC+9 m=+0.016000001 # not broken

# tinygo-date-example
$ curl http://localhost:8787/now
2078-01-01 14:39:27.168999936 +0900 UTC+9 m=+3408241167.168999937 # broken

remote result

# go-date-example
$  curl https://go-date-example.syumai.workers.dev/now 
2024-01-01 14:56:29.363 +0000 UTC+0 m=+0.000000001 # not broken

# tinygo-date-example
$ curl https://tinygo-date-example.syumai.workers.dev/now
2024-01-01 14:56:33.423000064 +0000 UTC+0 m=+1704120993.423000065 # not broken

syumai avatar Jan 01 '24 15:01 syumai

Alternatively, you can use the Date class directly.

Example code

https://github.com/syumai/workers-playground/blob/0828c616610cadff6c09b4d4be534fe56e4500b6/tinygo-date-example/main.go#L15-L19

result

$ curl http://localhost:8787/now
2078-01-01 15:25:45.472 +0900 UTC+9 m=+3408243945.472000001 # broken
$ curl http://localhost:8787/date
2024-01-01T15:14:10.439Z # not broken

syumai avatar Jan 01 '24 15:01 syumai

According to this issue, in local worker development, performance.now() behaves the same as Date.now(). Originally, performance.now() is supposed to return the time elapsed since the start of the script execution, but it seems that the behavior is different in this case (local dev env). https://github.com/cloudflare/workerd/issues/390

TinyGo's time.Now() is calculated by Date.now() + performance.now(). Therefore, time.Now() in the local environment is the only case of the broken value.

					// func ticks() float64
					"runtime.ticks": () => {
						return timeOrigin + performance.now();
					},

https://github.com/tinygo-org/tinygo/blob/731532cd2b6353b60b443343b51296ec0fafae09/targets/wasm_exec.js#L290

syumai avatar Jan 02 '24 14:01 syumai