Using Native Date Methods
One way to increment a date with JavaScript is to use native JavaScript date methods.
We can use the setDate
method to increment a date with JavaScript.
For instance, we can write:
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
We call setDate
with the current date plus 1.
To get the current date, we get the getDate
method.
Then tomorrow
would be tomorrow’s date.
Also, we can add milliseconds with the getTime
method and add 1 day in milliseconds.
For instance, we can write:
const tomorrow = new Date();
tomorrow.setTime(tomorrow.getTime() + 1000 * 60 * 60 * 24);
We call setTime
to let us set a time with a timestamp in milliseconds.
In the method call, we call getTime
to return the timestamp in milliseconds.
And we add the 1 day in milliseconds to it with 1000 * 60 * 60 * 24
.
And so we get the same result as before.
Using Moment.js
Another way to increment a JavaScript date is to use the moment.js library.
To use it, we write:
const today = moment();
const tomorrow = moment(today).add(1, 'days');
We call the moment
function with no arguments to create a moment object with the current date and time.
Then we call add
on the current date to add a day to it.
We pass in the quantity and the unit to add.