dayjs - NPM Command
dayjs is a lightweight JavaScript library that simplifies date manipulation and formatting. It is often considered a modern alternative to the popular Moment.js library due to its small size and similar API.
These are the following topics that we are going to discuss:
Table of Content
What is dayjs?
dayjs is a JavaScript library that provides an easy-to-use API for working with dates and times. It offers functionality similar to Moment.js but is much smaller in size (just 2KB), making it ideal for projects where you need to minimize the size of your bundle. Some of the main features of dayjs include:
- Parsing and formatting dates
- Date manipulation (adding, subtracting)
- Date comparison
- Timezone support through plugins
- Immutability (methods don’t modify the original date object)
Steps For Installing dayjs
Step 1: Create the project by using the command
mkdir dayjs-example
cd dayjs-example
Step 2: Initialize the project
npm init -y
Step 3: Install dayjs using NPM
npm install dayjs
Project Structure
Updated Dependencies
"dependencies": {
"dayjs": "^1.11.13"
}
Common Date Operations with dayjs
Formatting Dates
dayjs allows you to format dates in a variety of ways. The format() method can be used to convert a date object into a string with a specified format.
Example: In this example we will be formatting dates
//index.js
const dayjs = require('dayjs');
const now = dayjs();
console.log(now.format('YYYY-MM-DD'));
console.log(now.format('dddd, MMMM D, YYYY h:mm A'));
Output:
2024-10-08
Tuesday, October 8, 2024 10:25 AM
Parsing Dates
You can also parse dates from strings using dayjs. It supports ISO 8601 date strings and many other formats.
Example: In this example we will parse dates
//index.js
const dayjs = require('dayjs');
const date = dayjs('2024-10-08');
console.log(date.format());
Output:
2024-10-08T00:00:00-07:00
Manipulating Dates
dayjs allows you to manipulate dates by adding or subtracting time.
Example: Adding time to a date
//index.js
const dayjs = require('dayjs');
const nextWeek = dayjs().add(7, 'day');
console.log(nextWeek.format('YYYY-MM-DD'));
Output:
2024-10-15
Comparing Dates
Comparing dates in dayjs is simple using methods like isBefore(), isAfter(), and isSame().
Example: In this example we will be comparing the dates
//index.js
const dayjs = require('dayjs');
const date1 = dayjs('2024-10-08');
const date2 = dayjs('2023-10-08');
console.log(date1.isAfter(date2));
console.log(date1.isBefore(date2));
console.log(date1.isSame('2024-10-08'));
Output:
true
false
true
Conclusion
dayjs is a fantastic, lightweight JavaScript library for managing dates and times in your projects. With a minimal footprint and an intuitive API, it offers a simple yet powerful solution for developers who need to handle dates efficiently. Whether you're formatting dates, manipulating time, or adding timezone support through plugins, dayjs provides all the essential features you need.