My current datetime is April 8th, 8:52 PM, and I'm using this code:
//get current time
var now = new Date();
//get current time plus 6 hours in the future
var future = new Date(now.getFullYear(), now.getMonth(), now.getDay(), now.getHours()+6, now.getMinutes(), now.getSeconds(), 0);
//print result
console.log(future.toLocaleString());
The result is 4/6/2016, 2:52:43 AM
. The time is actually correct, but the day is somehow going backwards 2 days. What am I doing wrong?
.getDay()
returns the day of the week (0-6).
What you want is .getDate()
instead, which returns the day of the month.
If you are going to do a lot of date manipulation, you should check out Moment.js
In moment you can just do:
var future = moment.add(6, 'hours');