Skip to content
the poor coder

add 2 for hours in date timestamp js

Poor Man
Published
Reading time
2 min read

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:

Text

// 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:

Text

// 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:

Text

// 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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC