I have an android app and a web app which are connected together. On clicking a button in the web app, a notification is instantly sent to the android app. The moment the button on the web app is clicked, I need to record the current time in both apps.
On the web app I'm using Date.now() to record the time. And in the android app I'm using System.currentTimeMillis() to record the time. When the button is clicked in the web app, it only takes a couple seconds for the notification to reach the android app. Hence, the time recorded in both places must differ by only a few seconds.
But the following timestamps are getting recorded in both places:
Web app- using Date.now() - 1653945533308
Android app- using System.currentTimeMillis() - 1653945810727
These timestamps have a difference of 5 minutes, which is wrong. It looks like for some reason, the timestamps getting logged by the 2 apis are not exactly the same at the same time.
Why is this happening? Is there a way to ensure that "Date.now() in javascript" and "System.currentTimeMillis() in java" both record the same timestamp at the same time?
As @RobbyCornelissen is onto, this is probably related to systems clocks. JavaScript Date can only be as accurate as the clock of the system it's running on. See this relevant question for a brief discussion on the topic. The same goes for Java, and there is also a discussion in the Java Docs about discrepancies between system time and UTC time. I'm assuming you're running your android-app on some sort of emulator of physical device, so that might be were the system time differs.
Programatically, you could, depending on the use case, always solve this by passing the clock/date from the web-app to the API, or the other way around. Clocks have always been an issue on computer design, and there is a bunch of research on it, so you should have no difficulties stumbling upon some similar issue in the litterature.