DEV Community

Ankit Utekar
Ankit Utekar

Posted on

What is the *legit* way to get the current date and time of system ?

Yes, the title is a bit weird, but read on, I have an interesting story to tell.
Recently at work I was tasked with implementing a timer. It was fairly simple, at least that's what I thought. User performs some action -> an event is fired to the backend -> backend does some computations, saves the data along with current date-time and returns response including recorded date-time -> browser starts the timer after response has been received. Timer was supposed to run for 1 hour from the time when event happened in the backend.
The problem was, my system clock was set to run 8 seconds behind actual clock. As result of this, timer would consider extra 8 seconds.
We had server side validations, so even though user could perform action after timer has been ended, we were good.
My question is, is there any better alternative than relying on client system to get current date time ? Do you use server side timings/ third party services for these things ? If yes, what about network latency ? How does systems like online examination system handle it ?

Top comments (3)

Collapse
 
bitsrfr profile image
Joseph

Unfortunately, there's not really a better way to do it.

You can use a time API to get the global time. Essentially that pulls the time from a server that it synced with a global/atomic clock.

However, the time that returns may still have some delay depending on the network connection.

Collapse
 
bgadrian profile image
Adrian B.G.

One way would be to let the timer to be on server side and let it send you a push notification/trigger.

Other way would be to check the time on server and add the request time, from time to time.

When handling the time in a browser keep in mind

  • the interval can be negative, the user can change the hour, time minute and date during your timer
  • the browser can postpone/freeze your timers based on focus, CPU usage etc
Collapse
 
nektro profile image
Meghan (she/her)