I’m trying to build a real-time countdown clock in my Cocos Creator-based app.
It is supposed to not pause when users leave the app (e.g. on iOS or Android) - rather, after resuming the app, the time that has passed in the meantime should be subtracted from the countdown. (That is: no ‘cheating’ the countdown by leaving the app.)
What would a ‘update()’ function look like for this?
Any advice (accessing the device’s clock, or so) is welcome.
now comes the tricky part, you have to convert your duration into days, hours, minutes, and seconds by using time base math: for example a day is (24 * 60 * 60 * 1000) milliseconds long, so then you divide your duration by millisecondsPerDay,
then for each subsequent unit of measure, in this case it would be hours after days, you need to subtract away how many days you just tallied and then do the same math on the new duration but for hours
var millisecondsPerDay = 24 * 60 * 60 * 1000;
var millisecondsPerHour = 60 * 60 * 1000;
var millisecondsPerMinute = 60 * 1000;
var days = Math.floor(duration / millisecondsPerDay);
var hours = Math.floor((duration - days * millisecondsPerDay) / millisecondsPerHour);
var minutes = Math.floor((duration - days * millisecondsPerDay - hours * millisecondsPerHour) / millisecondsPerMinute);
var seconds = Math.floor((duration - days * millisecondsPerDay - hours * millisecondsPerHour - minutes * millisecondsPerMinute) / 1000);