Guide To Learn Dayjs

Shameel Uddin - Nov 8 '23 - - Dev Community

Introduction

Playing with dates in JavaScript is a difficult task which is why there are supporting libraries, one of the most famous is moment.js which has become a legacy project as we discussed earlier.
One of the proposed alternatives is day.js which itself is cool library to work efficiently with dates. I have used it for over a year and have gained good grasp over it.

Why should you go with Day.js?

  • Millions of downloads
  • Actively maintained
  • Easier to work with
  • 2kB alternative to Moment.js + Moment.js compatible APIs
  • Works with browser + Node.js
  • Returns new instance (prevents bugs)

Getting Started With Dayjs

It is very simple. You can find the guide for Node.js here and for Browser, you can find it here. If you are into TypeScript like myself, this should help you setting dayjs up.

I am working with Node.js in JavaScript enviorment. The version of dayjs is ^1.11.10. Mentioning it here since any breaking change could be introduced in the future.

If you are following this guide, please do this:

Prepare your environment:



npm init


Enter fullscreen mode Exit fullscreen mode

Install dayjs with the exact version:



npm install dayjs@1.11.10


Enter fullscreen mode Exit fullscreen mode

Create a file "index.js" and import dayjs:



const dayjs = require('dayjs')


Enter fullscreen mode Exit fullscreen mode

This is my minimalistic setup for preparing this guide:

Image description

Dayjs Basics

Wrapper of Date object is created by Day.js. Day.js object itself is immutable (i.e., cannot be changed). Any API operation performed in it for manipulation or any other purpose will return new instance.

Dayjs() Object For Current Time

Lets explore dayjs a bit:



console.log(dayjs());


Enter fullscreen mode Exit fullscreen mode

It is exactly same as this:



console.log(dayjs(new Date()));


Enter fullscreen mode Exit fullscreen mode

It returns this current date in this object format:



{
  '$L': 'en',
  '$d': 2023-11-07T09:49:35.970Z,
  '$y': 2023,
  '$M': 10,
  '$D': 7,
  '$W': 2,
  '$H': 14,
  '$m': 49,
  '$s': 35,
  '$ms': 970,
  '$x': {},
  '$isDayjsObject': true
}


Enter fullscreen mode Exit fullscreen mode

Dayjs Object For Specific Time

We can also politely ask dayjs to return the object for the date of our choice... Like this:



dayjs('12-12-2023');


Enter fullscreen mode Exit fullscreen mode

or like this:



dayjs(new Date(2023, 8, 8))


Enter fullscreen mode Exit fullscreen mode

It returns this:



{
  '$L': 'en',
  '$d': 2023-12-11T19:00:00.000Z,
  '$y': 2023,
  '$M': 11,
  '$D': 12,
  '$W': 2,
  '$H': 0,
  '$m': 0,
  '$s': 0,
  '$ms': 0,
  '$x': {},
  '$isDayjsObject': true
}


Enter fullscreen mode Exit fullscreen mode

Formatting Dates

Dayjs provides multitude of options for you to format the date which you want to display to the users.

For example, this:



dayjs('2023-12-23').format('DD/MM/YYYY') // '23/12/2023'


Enter fullscreen mode Exit fullscreen mode

You can find the entire table for formatting here.

Working with plugins

Dayjs provides set of plugins which helps your tasks easier.

In order to work with plugins, you have to first import it and then extend it with day.js like this:



const dayjs = require("dayjs");
const isToday = require("dayjs/plugin/isToday");
dayjs.extend(isToday);
console.log(dayjs("11-07-2023").isToday()); // true


Enter fullscreen mode Exit fullscreen mode

The plugin above will help you determine if the date entered is of today or not.

Cool plugins

Some of the really cool ones which can help you save hours (if working with native dates) are as follows:

Following will help you determine if the provided date is of yesterday, today or tomorrow by returning a boolean response:

  • isToday
  • isYesterday
  • isTomorrow

You should explore other ones as per your project needs here.

Display Options

You can display dayjs objects as follows:

JavaScript Date



console.log(dayjs("2023-12-23").toDate());


Enter fullscreen mode Exit fullscreen mode

String



dayjs('2019-01-25').toString() // 'Fri, 25 Jan 2019 02:00:00 GMT'


Enter fullscreen mode Exit fullscreen mode

JSON



dayjs('2023-01-12').toJSON() // '2023-01-12T02:00:00.000Z'


Enter fullscreen mode Exit fullscreen mode

Array



dayjs.extend(toArray)

dayjs('2023-01-12').toArray() // [ 2023, 0, 12, 0, 0, 0, 0 ]


Enter fullscreen mode Exit fullscreen mode

Object



dayjs.extend(toObject)

dayjs('2023-01-23').toObject()
/* { years: 2023,
     months: 0,
     date: 23,
     hours: 0,
     minutes: 0,
     seconds: 0,
     milliseconds: 0 } */


Enter fullscreen mode Exit fullscreen mode

Manipulation

You can do any sort of manipulation. Like adding or subtracting time of any format with the Date object.

Adding Time

You can add time like this:



const date1 = dayjs();
const date2 = date1.add(2, "day");
console.log(date2);


Enter fullscreen mode Exit fullscreen mode

date1 is not changed when date1.add is applied. This is what I meant by immutability earlier.

Subtracting Time

Subtraction happens like this:



const date1 = dayjs();
const date2 = date1.subtract(2, "day");
console.log(date2);


Enter fullscreen mode Exit fullscreen mode

Finding Start or End of Time

Dayjs allows you to find start or end of the month or year. Mostly it's used for months.



dayjs().startOf('year')
dayjs().endOf('year')


Enter fullscreen mode Exit fullscreen mode

Finding Difference Between Two Dates:

This is something which is somehow used in many projects so I thought to mention this scenario in the guide as well.
You can find the differences between the two dates like this:



const firstDate = dayjs("2023-06-20");
const secondDate = dayjs("2022-11-11");
console.log(firstDate.diff(secondDate));


Enter fullscreen mode Exit fullscreen mode

By default it gives response in milliseconds:



19094400000


Enter fullscreen mode Exit fullscreen mode

But you can also change it to day, month or year.
For example like this:



firstDate.diff(secondDate, "month") // 7


Enter fullscreen mode Exit fullscreen mode

If you want a very specific answer with decimal points value then do this:



firstDate.diff(secondDate, "month", true) // 7.290322580645161


Enter fullscreen mode Exit fullscreen mode

Working with UTC

In my project, I had to work with UTC because of tiemzone issues. Dayjs provide seamless solution for this with the help of plugin.

From official docs here, you can see, it works as simple as this:



dayjs.extend(utc)

var a = dayjs()
a.format() //2019-03-06T08:00:00+08:00
a.utc().format() // 2019-03-06T00:00:00Z


Enter fullscreen mode Exit fullscreen mode

Timezone

You can also work with multiple timezones with the help of another super cool plugin.

Mentioning the example from official docs here:



dayjs.extend(utc)
dayjs.extend(timezone)

// current time zone is 'Europe/Berlin' (offset +01:00)
// Parsing
dayjs.tz("2013-11-18 11:55:20", "America/Toronto") // '2013-11-18T11:55:20-05:00'

// Converting (from time zone 'Europe/Berlin'!)
dayjs("2013-11-18 11:55:20").tz("America/Toronto") // '2013-11-18T05:55:20-05:00'


Enter fullscreen mode Exit fullscreen mode

We used to store the timezone of the user in database and then use the string in .tz method to get the timezone of the user and have it displayed.

It can also be used to guess the timezone of the user. Like this:



dayjs.tz.guess() // America/Chicago

Enter fullscreen mode Exit fullscreen mode




i18n

If your project includes internationalization then don't worry. Dayjs got you covered here as well.

You can find how to load it in Node.js project here and for browser, you can find the details here.

This gives you access to locale which you can either use for instance or in global manner. The details are mentioned in the docs mentioned above.

Conclusion

This blog serves as a guide for you to decide whether you should choose dayjs for your next project or not. I tried to include what I used in my own project over the year.

Happy coding! 🎉💻✨

Follow me for more such content:
LinkedIn: https://www.linkedin.com/in/shameeluddin/
Github: https://github.com/Shameel123

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player