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.
Parsing JavaScript Native Date Objects
We can pass in native JavaScript date objects as an argument of the dayjs
function.
To do this, we write:
const d = new Date(2020, 8, 18)
const dt = dayjs(d)
console.log(dt)
Parsing Plain JavaScript Objects into Dates
To parse plain JavaScript objects into dates, we can use the objectSupport
plugin.
For instance, we can write:
const dayjs = require("dayjs");
const objectSupport = require("dayjs/plugin/objectSupport");
dayjs.extend(objectSupport);
const dt = dayjs({
year: 2020,
month: 3,
day: 5,
hour: 15,
minute: 10,
second: 3,
millisecond: 123
});
console.log(dt);
We import the dayjs
and dayjs/plugin/objectSupport
modules to add the day.js library with the objectSupport
plugin.
Then we add:
dayjs.extend(objectSupport);
to add the objectSupport
plugin.
Now we can pass in an object into the dayjs
function to parse it into a date.
Parsing JavaScript Array into Dates
Day.js also comes with the ArraySupport
plugin that lets us parse an array of numbers into dates.
For instance, we can write:
const dayjs = require("dayjs");
const arraySupport = require("dayjs/plugin/arraySupport");
dayjs.extend(arraySupport);
const dt = dayjs([2020, 1, 14, 15, 25, 50, 125]);
console.log(dt);
to import the Day.js and arraySupport
library respectively in the first 2 lines.
Then we add:
dayjs.extend(arraySupport);
to add the arraySupport
plugin.
Now we can pass in an array into the dayjs
function to parse the array into a date.
The order of the numbers in the array is year, month, day of the month, hour, minutes, seconds, and milliseconds.
Conclusion
Day.js is a JavaScript library that lets us manipulate dates in our apps.