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.
Get the Time from Now
We get the time from now with a Day.js date by using the fromNow
method available with the relativeTime
plugin.
For instance, we can write:
const dayjs = require("dayjs");
const relativeTime = require("dayjs/plugin/relativeTime");
dayjs.extend(relativeTime);
const result = dayjs("2000-01-01").fromNow();
console.log(result);
Then we get '22 years ago‘
as the value of result
in year 2021.
We can also pass in true
to fromNow
to remove the suffix from the returned string.
For instance, we can write:
const dayjs = require("dayjs");
const relativeTime = require("dayjs/plugin/relativeTime");
dayjs.extend(relativeTime);
const result = dayjs("2000-01-01").fromNow(true);
console.log(result);
Then result
is '22 years'
in year 2021.
Get the Time Relative to a Given Time
We can get the time relative to the given time with the from
method.
For instance, we can write:
const dayjs = require("dayjs");
const relativeTime = require("dayjs/plugin/relativeTime");
dayjs.extend(relativeTime);
const a = dayjs("2020-01-01");
const result = dayjs("1999-01-01").from(a);
console.log(result);
Then we get the time difference between a
and January 1, 1999.
Therefore, result
is '21 years ago‘
.
We can get the relative time string without the suffix if we pass in true
as the 2nd argument of from
.
Conclusion
Day.js is a JavaScript library that lets us manipulate dates in our apps.