Day.js is a JavaScript library that lets us manipulate dates in our apps.
In this article, we’ll look at how to use Day.js to manipulate dates in our JavaScript apps.
Add or Subtract a Given Amount of Time
We can add a given amount of time to our Day.js date object with the add method.
For instance, we can write:
const dayjs = require("dayjs");
const result = dayjs().add(7, "day");
console.log(result);
to add 7 days to the current date-time.
We call the add method with one of 'year' , 'month' , 'date' , 'hour' , 'minute' , 'second' , and 'millisecond' unit values as the first argument.
The 2nd argument is the value to set.
The month starts with 0 for January just like JavaScript dates.
There’re also shorthands for each argument string.
'y' is shorthand for 'year' .
'M' is shorthand for 'month' .
'D' is shorthand for 'date' .
'd' is shorthand for 'day' , which is the day of the week. It starts at 0 for Sunday, and 6 is Saturday.
'h' is shorthand for 'hour' .
'm' is shorthand for 'minute' .
's' is shorthand for 'second' .
And 'ms' is shorthand for 'millisecond' .
We can replace add with subtract and keep the same arguments to subtract a given amount of time.
Conclusion
Day.js is a JavaScript library that lets us manipulate dates in our apps.