Categories
Day.js

Getting Started with Manipulating Dates with Day.js

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.

Installation

We can install Day.js for Node.js or TypeScript apps by running:

npm install dayjs

If we use it in our TypeScript project, then we must add the following to compiler options to tsconfig.json :

{  
  "compilerOptions": {  
    "esModuleInterop": true,  
    "allowSyntheticDefaultImports": true,  
  }  
}

If we want to use it in the browser, we can add the script tag version of it with:

<script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script>

Parsing Dates

We can create a Day.js date object with the dayjs function:

const now = dayjs()  
console.log(now)

This creates a Day.js date object with the current date and time.

We can also pass in a date string into the dayjs function:

const dt = dayjs('2020-04-04T16:00:00.000Z')  
console.log(dt)

And dt is a Day.js object with the given date.

We can also specify the date string’s format when we’re parsing it:

const dt = dayjs('05/02/20 1:02:03 PM -05:00', 'MM/DD/YY H:mm:ss A Z')  
console.log(dt)

Timestamps can also be parsed into a Day.js date object:

const dt = dayjs(1318781876406)  
console.log(dt)

To parse a date from the timestamp converted to a number of seconds, we can use the unix method:

const dt = dayjs.unix(1318781876.721)  
console.log(dt)

Conclusion

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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