add 2 for hours in date timestamp js
Adding 2 Hours in Date Timestamp using JavaScript
If you want to add 2 hours to a date timestamp in JavaScript, you can use the Date
object and its setHours()
method. Here's how to do it:
// Create a new Date object
var date = new Date();
// Get the current hours
var hours = date.getHours();
// Add 2 hours to the current time
date.setHours(hours + 2);
// Output the new date timestamp
console.log(date);
In the code above, we first create a new Date object that represents the current time. We then use the getHours()
method to get the current number of hours. Finally, we use the setHours()
method to add 2 hours to the current time.
You can also directly specify the number of hours you want to add by passing it as a parameter to the setHours()
method. For example:
// Create a new Date object
var date = new Date();
// Add 2 hours to the current time
date.setHours(date.getHours() + 2);
// Output the new date timestamp
console.log(date);
In this example, we directly pass the value of date.getHours() + 2
as a parameter to the setHours()
method.
It's important to note that the setHours()
method modifies the original Date object. If you want to create a new Date object with the added hours, you can do it like this:
// Create a new Date object
var date = new Date();
// Create a new Date object with 2 hours added
var newDate = new Date(date.getTime() + (2 * 60 * 60 * 1000));
// Output the new date timestamp
console.log(newDate);
In this example, we first get the current time in milliseconds using the getTime()
method. We then add 2 hours' worth of milliseconds (2 * 60 * 60 * 1000) and create a new Date object with the resulting time.