Horje
How to use the DayJS Library to work with Date & Time in JavaScript?

JavaScript has various useful packages for working with date and time. One such library is DayJS, which provides a simple and proper way to manipulate, format, and parse dates in JavaScript applications.

Prerequisites:

Steps to Create Application and Installing Package

Step 1: Create a new folder for your project and navigate into it.

mkdir day-JS
cd day-JS

Step 2: Initialize npm to create a package.json file.

npm init -y

Step 3: Install dayjs package using below command.

npm install dayjs

Project Structure:

PS

Project Structure

Approach

  • First, Create directory day-JS, create package.json file and Install dayjs package.
  • Then, import DayJS using require(‘dayjs’), get the current date and time using dayjs().
  • Format and display it using now.format(‘YYYY-MM-DD HH:mm:ss’).

Updated Dependencies:

"dependencies": {
"dayjs": "^1.11.11"
}

Example 1: The example below shows the use of DayJS Library to work with Date and Time in JS.

JavaScript
// index.js

// Importing DayJS library
const dayjs = require('dayjs');

// Getting the current date and time
const now = dayjs();

// Displaying the current date and time
console.log(now.format('YYYY-MM-DD HH:mm:ss'));

Output:

OP1

Output

Example 2: In this example, we are using the DayJS library to calculate the difference in days between two dates. We import DayJS using require(‘dayjs’), create two date objects, calculate the difference with date2.diff(date1, ‘days’), and then display the result along with the formatted dates.

JavaScript
// index.js

const dayjs = require('dayjs');
const date1 = dayjs('2024-05-17');
const date2 = dayjs('2024-05-20');

// Calculating the difference in days 
// between the two dates
const res = date2.diff(date1, 'days');

// Displaying the difference in days
console.log(`The difference between ${date1.format('YYYY-MM-DD')}
and ${date2.format('YYYY-MM-DD')} is ${res} days.`);

Output:

Op2



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
JavaScript Program to Remove Empty Strings from Array Without Loop JavaScript Program to Remove Empty Strings from Array Without Loop
How to Compare Objects for Equality in JavaScript? How to Compare Objects for Equality in JavaScript?
Math Sprint Game in VueJS Math Sprint Game in VueJS
Compute the Bitwise AND of all Numbers in a Range using JavaScript Compute the Bitwise AND of all Numbers in a Range using JavaScript
JavaScript Program to Calculate the Surface Area of a Triangular Prism JavaScript Program to Calculate the Surface Area of a Triangular Prism

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16