Skip to content
the poor coder

jquery add hours to date

Poor Man
Published
Reading time
1 min read
On this page

Adding Hours to Date using jQuery#

If you want to add hours to a date using jQuery, you first need to get the current date and then add the desired number of hours to it. Here are two ways to do it:

Method 1: Using the `getTime()` and `setTime()` Methods#

The first method involves using the `getTime()` and `setTime()` methods. Here's the code:

Text

  // Get the current date
  var currentDate = new Date();
  
  // Add 5 hours to the current date
  var hoursToAdd = 5;
  var newDate = new Date(currentDate.getTime() + hoursToAdd * 60 * 60 * 1000);

Here, the `getTime()` method returns the number of milliseconds since January 1, 1970, and the `setTime()` method sets the date to a specified time. So we add the desired number of hours in milliseconds (by multiplying `hoursToAdd` by 60 * 60 * 1000) to the current date's timestamp and pass it to a new `Date` object.

Method 2: Using the `getHours()` and `setHours()` Methods#

The second method involves using the `getHours()` and `setHours()` methods. Here's the code:

Text

  // Get the current date
  var currentDate = new Date();
  
  // Add 5 hours to the current date
  var hoursToAdd = 5;
  var newDate = new Date(currentDate.setHours(currentDate.getHours() + hoursToAdd));

Here, we use the `getHours()` method to get the current hour of the day, add the desired number of hours to it, and pass it to the `setHours()` method to set the new hour value in the `Date` object.

You can choose whichever method suits your needs better. Both methods will give you the same result.

Conclusion#

So that's how you can add hours to a date using jQuery. Remember to use the `getTime()` and `setTime()` methods or the `getHours()` and `setHours()` methods based on your requirement.

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