How to get the remaining time from 24 hours in JavaScript

I have a problem, where I try to find the number of hours and minutes after I had last collected the item. For example, if I had collected the item 1 minute ago, the code should be able to print out the remaining time left to collect the item again(23 h and 59 m) in this format. Till now, I have worked out this much:

UserJSON is a JSON file with the user’s name and the time of their last claim

let deltaHour = Math.floor(new Date().getTime() - UserJSON[message.author.id].lastclaim) / (60 * 60 * 24)
let deltaRealHour = Math.floor(deltaHour)
let deltaMin = ((deltaHour % 1) / 100) * 60

Please help me out.

Answer

Here is a possible solution.

You can use the function I wrote before (timeUntilNextClaim()), supply it with the last time that your user claimed the item (in epoch seconds) and it will return to you the delta milliseconds until the item can be claimed.

You can then use the second funciton I wrote for you (toHrsAndMinutes) to turn milliseconds into hours and minutes (rounded down of course).

Please let me know if you have any questions or would like any more help with this. I’d be happy to help.

function timeUntilNextClaim(LastClaim) {
  /* this function takes an epoch time of the 
  last time the user claimed the item as an argument and 
  returns (in ms) the time until they can pick up the 
  item again */

  let now = new Date();
  // add 24 hours to last claim time to calculate next claim time
  let timeTilClaim = (LastClaim + 8.64e7) - now;
  if (timeTilClaim <= 0) {
    return 0;
  } else {
    return timeTilClaim;
  }
}

function toHrsAndMinutes(duration) {
  // this function will return an array of [hours, minutes] of a duration specified in ms
  var hours, minutes;
  hours = Math.floor(duration / 3.6e6);
  minutes = Math.floor((duration % 3.6e6) / 60000);
  return [hours, minutes];
}

function test() {
    // tests / Example Usage
    let usrLastClaimTime = new Date() - 20160000; // lets pretend they claimed it last 5.6 hours ago
    let now = new Date();
    let msTilNextClaim = timeUntilNextClaim(usrLastClaimTime);
    let hoursTilClaim, minsTilClaim;
    [hoursTilClaim, minsTilClaim] = toHrsAndMinutes(msTilNextClaim);

    console.log(`The current time is ${now}`);
    console.log(`The item was last claimed at ${Date(usrLastClaimTime)}`);
    console.log(`You can claim again in ${hoursTilClaim} Hours and ${minsTilClaim} Minutes`);
}
test();