Guide To Learn Dayjs
Tags: webdev, javascript, node, react
Published: 2023-11-08 06:25:47

## 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](url).
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](https://day.js.org/docs/en/installation/node-js) and for Browser, you can find it [here](https://day.js.org/docs/en/installation/browser). If you are into TypeScript like myself, [this](https://day.js.org/docs/en/installation/typescript) 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:
```js
npm init
```

Install dayjs with the exact version:
```js
npm install dayjs@1.11.10
```

Create a file "index.js" and import dayjs:
```js
const dayjs = require('dayjs')
```

This is my minimalistic setup for preparing this guide:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gt323b1uabzyyj6k9cco.png)

## 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:
```js
console.log(dayjs());
```
It is exactly same as this:
```js
console.log(dayjs(new Date()));
```
It returns this current date in this object format:
```js
{
  '$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
}
```
### Dayjs Object For Specific Time

We can also politely ask dayjs to return the object for the date of our choice... Like this:
```js
dayjs('12-12-2023');
```
or like this:
```js
dayjs(new Date(2023, 8, 8))
```
It returns this:
```js
{
  '$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
}
```

## Formatting Dates

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

For example, this:
```js
dayjs('2023-12-23').format('DD/MM/YYYY') // '23/12/2023'
```

You can find the entire table for formatting [here](https://day.js.org/docs/en/display/format).

## 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:

```js
const dayjs = require("dayjs");
const isToday = require("dayjs/plugin/isToday");
dayjs.extend(isToday);
console.log(dayjs("11-07-2023").isToday()); // true
```
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](https://day.js.org/docs/en/plugin/plugin).
 
## Display Options

You can display `dayjs` objects as follows:

### JavaScript Date

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

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

### JSON
```js
dayjs('2023-01-12').toJSON() // '2023-01-12T02:00:00.000Z'
```
### Array
```js
dayjs.extend(toArray)

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


### Object
```js
dayjs.extend(toObject)

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

## 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:
```js
const date1 = dayjs();
const date2 = date1.add(2, "day");
console.log(date2);
```
`date1` is not changed when `date1.add` is applied. This is what I meant by `immutability` earlier.

### Subtracting Time

Subtraction happens like this:

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

## 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.

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


## 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:
```js
const firstDate = dayjs("2023-06-20");
const secondDate = dayjs("2022-11-11");
console.log(firstDate.diff(secondDate));
```

By default it gives response in milliseconds:
```
19094400000
```
But you can also change it to `day`, `month` or `year`.
For example like this:
```js
firstDate.diff(secondDate, "month") // 7
```
If you want a very specific answer with decimal points value then do this:
```js
firstDate.diff(secondDate, "month", true) // 7.290322580645161
```

## 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](https://day.js.org/docs/en/manipulate/utc), you can see, it works as simple as this:
```js
dayjs.extend(utc)

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

## Timezone 

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

Mentioning the example from official docs here:

```js
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'
```

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:
```js
dayjs.tz.guess() // America/Chicago
```

## 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](https://day.js.org/docs/en/i18n/loading-into-nodejs) and for browser, you can find the details [here](https://day.js.org/docs/en/i18n/loading-into-browser).

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