Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 8, 2022 08:57 am GMT

Day.js a cool library for working with Dates in JavaScript

In the previous article, we discussed JavaScript date libraries which make working with date & time easy. Working with dates isn't so hard although it wasted a lot of my time so, during the last hackathon project I found this cool library.

How to install ?
Use the npm install dayjs command

Day.js also ships with Typescript declaration in the npm package, if you feel trouble while importing Day.js then check out the guide here

excited

Can't wait, excited! lets gooooo...

How Dayjs is different from the native Date.prototype?
Instead of modifying the native JavaScript Date object it creates a wrapper around it & returns an immutable object. If we apply any operations on this object it will return a new instance of it.

Confused
You might get confused about what the immutable date object Dayjs gives us & how it is different from a regular JavaScript date object which is mutable. So let's kick off the confusion & understand it with a clear example.

let d = new Date();console.log(d);  // 2022-06-06T08:13:28.387Zlet d1 = d.setMonth(2);console.log(d); // 2022-03-06T08:13:28.387Z// value of object changed.
let d = dayjs();console.log(d); // {  '$L': 'en',  '$d': 2022-06-06T08:13:28.391Z,  '$x': {},  '$y': 2022,  '$M': 5,  '$D': 6,  '$W': 1,  '$H': 13,  '$m': 43,  '$s': 28,  '$ms': 391}let d1 = dayjs.set('month',2);console.log(d); // {  '$L': 'en',  '$d': 2022-06-06T08:13:28.391Z,  '$x': {},  '$y': 2022,  '$M': 5,  '$D': 6,  '$W': 1,  '$H': 13,  '$m': 43,  '$s': 28,  '$ms': 391}// value of object remains same.

What does the above example do?
In both coding examples, we create first a date object and then set the month value to 2. If you see the output of the console you will find the object we created in the first code gets modified but the object we created using Day.js keep remains the same after the operation so, it shows the immutability of the Day.js.

Now we have understood how Day.js is different from the native JS date object so let's move ahead & understand Day.js with the help of a few examples.

How to get the current date object using Dayjs ?

import dayjs from 'dayjs';const d = dayjs();console.log(d);// {  '$L': 'en',  '$d': 2022-06-06T08:13:28.391Z,  '$x': {},  '$y': 2022,  '$M': 5,  '$D': 6,  '$W': 1,  '$H': 13,  '$m': 43,  '$s': 28,  '$ms': 391}
  • The object contains lots of helpful properties such as year, month, date, hours, minutes, seconds & more.

How to convert a UNIX Timestamp into a nice Dayjs object?

const timeStampValue = 1318781876406  // in millisecondsconst d = dayjs(timeStampValue);
  • TimeStamp value is also possible in seconds.

How to create a Day.js object with a pre-existing date?

const d = new Date(2018, 8, 18)const day = dayjs(d)

How to validate a value whether the Dayjs's date is valid?

const isValid = dayjs('2022-06-06').isValid; console.log(isValid);  // true

How to get a particular value like Milliseconds, Hour, Month, Minute....?

  • Get the Milliseconds from the current time
dayjs().millisecond()
  • Get the Hour from the current time
dayjs().hour()
  • Get more details for fields such as Date of the month & Day of the week read here;

How to perform addition & substraction with dayjs object ?

  • Adding 1 day in the current time
dayjs().add(1,'day');
  • Subtracting 1 year from the current time
dayjs().subtract(1,'year')

How to display the current time in Day,DD/MM/YY format?

const d = dayjs();console.log(d.format('dddd, DD/MM/YY')); // Tuesday, 07/06/22
  • Where dddd returns the name of the day of the week, DD date, MM months & YY year. You can apply /, , or more symbols like these as a parameter. There are more formats available check out here

Up to now, we have discussed available methods & formats without any kind of plugin usage. Dayjs also supports a lot of useful plugins such as utc(for converting time in UTC), IsLeapYear(for checking Leap year or not) & much more...

How to install a plugin?

  • Day.js doesn't provide by default plugin support, although it provides plugin support in the same package but inside a plugin submodule. For example, If we need a UTC plugin that provides us time in UTC then we should extend something like below-
const dayjs = require("dayjs");  // import dayjsconst utc = require('dayjs/plugin/utc');  // import utc plugin dayjs.extend(utc) // connect the plugin with dayjs

How to get the week of the year with the help of the weekOfYear plugin?

const dayjs = require("dayjs");const weekOfYear = require("dayjs/plugin/weekOfYear); // import week of year plugindayjs.extend(weekOfYear);console.log(dayjs().week()); // returns week of the year

For more plugins checkout here

Here, I shared my learnings with Day.js, we discussed basic methods, formats & a little bit about plugins, although day.js provides more formats, and a timezone-based time feature that requires plugin support.


Original Link: https://dev.to/gulshanaggarwal/dayjs-a-cool-library-for-working-with-dates-in-javascript-h23

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To