This content originally appeared on Envato Tuts+ Tutorials and was authored by Sajal Soni
In this article, we’ll discuss how you can do date manipulations 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 to retrieve 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 to perform 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(); var numberOfMlSeconds = currentDateObj.getTime(); var addMlSeconds = 60 * 60000; 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 (60000).
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) { var numberOfMlSeconds = objDate.getTime(); var addMlSeconds = (intHours * 60) * 60000; var newDateObj = new Date(numberOfMlSeconds + addMlSeconds); return newDateObj; }
Here's how you can call it to get, for example, a date exactly one day in the future.
addHoursToDate(Date.now(), 24)
So that’s how you can use the getTime()
function to add time to a Date object in JavaScript. 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.
As we’ve already discussed in the previous section, you can use the getTime()
function to get the number of milliseconds from a Date
object. And thus, the logic of subtracting time from a Date
object is very similar to the add operation with the only exception that we need to subtract milliseconds instead of adding it.
Let’s go through the following example to see how it works.
function subtractTimeFromDate(objDate, intHours) { var numberOfMlSeconds = objDate.getTime(); var addMlSeconds = (intHours * 60) * 60000; var newDateObj = new Date(numberOfMlSeconds - addMlSeconds); return newDateObj; }
As you can see, it’s almost identical to the add operation with the only exception that we’re subtracting addMlSeconds
from numberOfMlSeconds
instead of adding it.
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 an 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!
You can test out the Moment.js library in this CodePen.
// display the current datetime console.log(moment().format()); // add '1' hour to the current datetime console.log(moment().add(1, 'h').format()); // add '30' minutes to the current datetime console.log(moment().add(30, 'm').format()); // 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 console.log(moment().subtract(1, 'h').format()); // subtract '30' minutes from the current datetime console.log(moment().subtract(30, 'm').format()); // subtract '1' day from the current datetime console.log(moment().subtract(1, 'd').format()); // subtract '1' week from the current datetime console.log(moment().subtract(1, 'w').format()); // subtract '3' months from the current datetime console.log(moment().subtract(3, 'M').format());
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.
You can use the CodePen below to experiment with different Moment utility methods and ways of adding or subtracting dates. For more reference, 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.
This content originally appeared on Envato Tuts+ Tutorials and was authored by Sajal Soni
Sajal Soni | Sciencx (2021-06-08T17:41:52+00:00) How to Add and Subtract Time From a Date in JavaScript. Retrieved from https://www.scien.cx/2021/06/08/how-to-add-and-subtract-time-from-a-date-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.