#timer in game

14 messages · Page 1 of 1 (latest)

fair turret
#

Hi I need help idk if this can work in gdevelop but is there a way that I can make a timer in days and it countdown the days for an event to end or start and when you exit the game it will still countdown just like in free free

hallow lynx
#

@fair turret what you can do is save a timestamp thats the current time+whatever you want to count too

hallow lynx
#
function addTime(addition, unit) {
  const currentTime = new Date();
  let futureTime;

  switch (unit) {
    case 'minutes':
      futureTime = new Date(currentTime.getTime() + addition * 60000);
      break;
    case 'hours':
      futureTime = new Date(currentTime.getTime() + addition * 3600000);
      break;
    case 'days':
      futureTime = new Date(currentTime.getTime() + addition * 86400000);
      break;
    default:
      return 'Invalid unit. Please provide "minutes", "hours", or "days".';
  }

  return futureTime.getTime(); // Return the future time in Date number format
}
#

then ```js
addTime(3, 'days')

#

so like ```js
let future=addTime(10,'days')

#
let Seconds=(future- Date.now())/1000
``` ==How many seconds left till that time
#

so all you do is you save that future variable and check what future-Date.now()/1000 is

#

once you get that that's the seconds

#
  var formatTime=(seconds)=> {
    const days = Math.floor(seconds / 86400);
    seconds %= 86400;
    const hours = Math.floor(seconds / 3600);
    seconds %= 3600;
    const minutes = Math.floor(seconds / 60);
    seconds %= 60;
    const parts = [];
    if (days > 0) parts.push(`${days} day${days > 1 ? 's' : ''}`);
    if (hours > 0) parts.push(`${hours} hour${hours > 1 ? 's' : ''}`);
    if (minutes > 0) parts.push(`${minutes} minute${minutes > 1 ? 's' : ''}`);
    if (seconds > 0) parts.push(`${seconds} second${seconds > 1 ? 's' : ''}`);
    if (parts.length === 0) return '0 seconds';
    if (parts.length === 1) return parts[0];
    const lastPart = parts.pop();
    return `${parts.join(', ')} and ${lastPart}`;
  }

#

then all you do is ```js
formatTime(863829.032)

#
'9 days, 23 hours, 57 minutes and 9.03200000000652 seconds'
#

will return this string

#

as the time gets less itl show less etc