5

How to Add and Subtract Time From a Date in JavaScript

 8 months ago
source link: https://webdesign.tutsplus.com/how-to-add-and-subtract-time-from-a-date-in-javascript--cms-37207t
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to Add and Subtract Time From a Date in JavaScript

In this post, I’ll show you how to manipulate the date with a JavaScript Date object. Specifically, we’ll see how you can add time to a Date object and subtract time from a Date object in JavaScript.

Often, you’ll need to work with dates and times in JavaScript. Luckily, JavaScript provides a built-in Date object which provides a lot of utility methods for date and time management. Although these methods are really useful for retrieving different elements of the date and time, a Date object doesn’t provide any methods that you can use to manipulate the date itself. In most cases, you can just use these methods to format the date and time for output.

In fact, if you want to perform operations on a Date object like adding time to or subtracting time from a date, there’s no easy way in vanilla JavaScript. Often, you’ll just end up implementing a custom solution which works for you. Alternately, you can use a date and time library like moment.js. Today, we’re going to discuss both ways of performing date manipulations in JavaScript.

How to Add Time to a JavaScript Date With Vanilla JavaScript

In this section, we’ll discuss how you can add time to a JavaScript Date object in vanilla JavaScript.

In JavaScript, the getTime() function returns the number of milliseconds since the Unix epoch time. That’s just a computer time convention that counts the number of seconds (milliseconds in JavaScript) since midnight UTC on January 1st, 1970.

Let’s try to understand how you can use the getTime() function to add time to a Date object in JavaScript. In the following example, we’ll add one hour to the existing Date object.

var currentDateObj = new Date();
2
var numberOfMlSeconds = currentDateObj.getTime();
3
var addMlSeconds = 60 * 60 * 1000;
4
var newDateObj = new Date(numberOfMlSeconds + addMlSeconds);

Firstly, we’ve initialized the currentDateObj variable with the current date, and it’s a Date object. Next, we’ve used the getTime() function to get the number of milliseconds from the currentDateObj object.

Next, we’ve calculated the number of milliseconds in an hour. Basically, we’ve just multiplied the number of minutes in an hour (60) by the number of seconds in a minute (60) by the number of milliseconds in a second (1000) to get the number of milliseconds in an hour.

As you might already know, you can initialize a Date object by providing the number of milliseconds as the first argument, and this would initialize a date object in reference to it. Thus, we’ve added numberOfMlSeconds and addMlSeconds to get the total number of milliseconds, and we’ve used it to initialize a new date object. And the end result is the newDateObj object, which should show a date ahead by one hour compared to the currentDateObj object.

In fact, you can go ahead and make a reusable function, as shown in the following snippet.

function addHoursToDate(objDate, intHours) {
2
    var numberOfMlSeconds = objDate;
3
    var addMlSeconds = (intHours * 60) * 60 * 1000;
4
    var newDateObj = new Date(numberOfMlSeconds + addMlSeconds);
5
6
    return newDateObj;
7
}

Here's how you can call it to get, for example, a date exactly one day in the future.

addHoursToDate(Date.now(), 24)
Date.now() already returns milliseconds, so no need to use getTime() in this scenario.

Try altering the hours value in the JavaScript panel below. Watch as the date outputted to the HTML tab changes.

You can also use the above function to add a number of days to an existing Date object; you just need to convert days to hours before calling the above function.

How to Subtract Time From a JavaScript Date With Vanilla JavaScript

In this section, we’ll see how you can subtract time from a JavaScript Date object.

The logic of subtracting time from a Date object is very similar to the add operation, except that we need to subtract milliseconds instead of adding them.

Let’s go through the following example to see how it works.

function subtractTimeFromDate(objDate, intHours) {
2
    var numberOfMlSeconds = objDate;
3
    var addMlSeconds = (intHours * 60) * 60 * 1000;
4
    var newDateObj = new Date(numberOfMlSeconds - addMlSeconds);
5
6
    return newDateObj;
7
}

As you can see, it’s almost identical to the add operation. The only difference is that we’re subtracting addMlSeconds from numberOfMlSeconds instead of adding.

How to Use the Moment.js Library to Perform Date Manipulations

In the previous section, we discussed how you can use vanilla JavaScript to perform date and time manipulations. If you don’t require any complex operations with a JavaScript Date object, you can live with vanilla JavaScript implementation. On the other hand, if your project requires you to perform different types of date and time manipulations, it’s better to use a third-party library which can make things easier for you.

Date and time can be surprisingly complicated. For example, think about adding a number of years to a date using the method above. It would be easy, if years were always the same length. However, in the real world, we have leap years. Similarly, if you want to add a number of months to a date, you'll have to know how many days each month has. 

In this section, we’ll see how you can use the Moment.js library, which provides a plethora of utility methods to manipulate a JavaScript Date object. Go ahead and download the Moment.js library, and you’re ready to use it!

With the Moment.js library you just need to call the moment() function to get the current date object. Once you get it, you can use different parsing methods for formatting and manipulation methods for manipulating the current date object.

// display the current datetime

2
console.log(moment().format());
3
4
// add '1' hour to the current datetime

5
console.log(moment().add(1, 'h').format());
6
7
// add '30' minutes to the current datetime

8
console.log(moment().add(30, 'm').format());
9
// add '2' days to the current datetime

console.log(moment().add(2, 'd').format());
// add '1' week to the current datetime

console.log(moment().add(1, 'w').format());
// add '1' month to the current datetime

console.log(moment().add(1, 'M').format());
// subtract '1' hour from the current datetime

20
console.log(moment().subtract(1, 'h').format());
21
22
// subtract '30' minutes from the current datetime

23
console.log(moment().subtract(30, 'm').format());
24
25
// subtract '1' day from the current datetime

26
console.log(moment().subtract(1, 'd').format());
27
28
// subtract '1' week from the current datetime

29
console.log(moment().subtract(1, 'w').format());
30
31
// subtract '3' months from the current datetime

32
console.log(moment().subtract(3, 'M').format());

You can use the CodePen below to experiment with different Moment utility methods and ways of adding or subtracting dates. For more information, I recommend you visit the official documentation.

So that’s how you can use the Moment.js library for formatting and manipulating dates.

Conclusion

Today, we discussed how you can perform date manipulations with a JavaScript Date object. Apart from vanilla JavaScript, we also explored the Moment.js library, which provides fairly easy ways to perform date manipulations.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK