Categories
Day.js

Manipulating Dates with Day.js — Calendar Time and Date-Time Difference

Spread the love

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.

Calendar Time

We can get a date in calendar time format with the calendar method that comes with the calendar plugin.

For instance, we can write:

const dayjs = require("dayjs");
const calendar = require("dayjs/plugin/calendar");
dayjs.extend(calendar);

const result = dayjs().calendar();
console.log(result);

We call calendar to get the time of today.

Therefore, if the time is 1:23 pm now, we get ‘Today at 1:23 PM‘ for result .

Date-Time Difference

We can get the date-time difference between 2 date-times with the diff method.

For instance, we can write:

const dayjs = require("dayjs");
const date1 = dayjs("2020-01-25");
const date2 = dayjs("2018-06-05");
const result = date1.diff(date2);
console.log(result);

to get the date difference between January 25, 2020, and June 5, 2018.

Therefore, result is 51757200000 and the number is in milliseconds.

We can get the date-time differences in a different unit.

For instance, we can get the difference in months by writing:

const dayjs = require("dayjs");
const date1 = dayjs("2020-01-25");
const date2 = dayjs("2018-06-05");
const result = date1.diff(date2, 'month');
console.log(result);

We passed in 'month' as the 2nd argument of diff to get the month difference between date1 and date2 .

Conclusion

Day.js is a JavaScript library that lets us manipulate dates in our apps.

Leave a Reply

Your email address will not be published. Required fields are marked *