Reputation: 1989
I am using the following in JS to find current Date Time -
var now = new Date();
now = now.format("dd/MM/yyyy, hh:mm tt");
Now I want to calculate by adding 2hrs to current instance of 'now'
var now = new Date();
var departureTime = new Date(now);
departureTime = departureTime.setHours(now.getHours() + 2);
now = now.format("dd/MM/yyyy, hh:mm tt");
departureTime = departureTime.format("dd/MM/yyyy, hh:mm tt");
However the formatting of departureTime is not correct... How can I add 2hrs to the current time and then display my result back as 1/28/2016 7:30 PM?
Upvotes: 1
Views: 124
Reputation: 19237
You can add 2 hours like this:
var now = new Date();
var d = new Date(now.getTime() + 2*60*60*1000);
// 1/28/2016 7:30 PM
var formattedDeparture = (d.getMonth()+1) + "/" + d.getDate()
+ "/" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes();
alert(now + " +2 hours is " + formattedDeparture);
This will format it with 24 hours, if you really need AM/PM, look at: How do you display javascript datetime in 12 hour AM/PM format? To format dateTime in different ways you can use this answer: How to format a JavaScript date
Upvotes: 2