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 Date to UTC Date
We can use the utc
plugin to parse a date into a UTC date.
For instance, we can write:
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
dayjs.extend(utc);
const dt = dayjs.utc().format();
console.log(dt);
to import the Day.js with the utc
plugin.
Then we can use the plugin by writing:
dayjs.extend(utc);
Now we can call the dayjs.utc
method to create a date object with the current date and time in UTC.
Clone a Date
We can clone a Day.js date object with the clone
method.
For instance, we can write:
const dayjs = require("dayjs");
const a = dayjs();
const b = a.clone();
console.log(a, b);
We call dayjs
to create date object a
.
Then we call clone
on a
and assign it to b
to make b
a clone of a
.
Validation
To validate a date, we can use the isValid
method.
It returns true
if the date is valid and false
otherwise.
For instance, we can write:
const dayjs = require("dayjs");
const isValid = dayjs().isValid();
console.log(isValid);
We call isValid
on a Day.js date object.
Since we called in a valid date, isValid
is true
.
Conclusion
Day.js is a JavaScript library that lets us manipulate dates in our apps.