-1

I have the following code to increment the hours in a date:

let timerExpireDate = new Date(countdownStartDate);
console.log(`original date is ${timerExpireDate}`);
console.log(`add on ${countdownHours} hours`);
timerExpireDate.setHours(timerExpireDate.getHours() + countdownHours);
console.log(`New date is ${timerExpireDate}`);

However it also seems to be incrementing the days by 6, here is the console log:

original date is Sun Jul 19 2020 16:36:39 GMT+0800 (Taipei Standard Time)
add on 2 hours
New date is Sat Jul 25 2020 18:36:39 GMT+0800 (Taipei Standard Time)

What am I doing wrong here?

Code
  • 6,041
  • 4
  • 35
  • 75
Kex
  • 8,023
  • 9
  • 56
  • 129

1 Answers1

2

It is likely that countdownHours is of type string instead of number, so timerExpireDate.getHours() + countdownHours is '162' (6 days later) instead of 18.

The fix is to cast countdownHours to number first, like countdownHours = +countdownHours.

Code
  • 6,041
  • 4
  • 35
  • 75