How to Calculate Local Time in Node.js ?
Last Updated :
03 Jul, 2024
Calculating local time in Node.js is a common requirement for many applications, especially those that operate across multiple time zones. Node.js, with its non-blocking, event-driven architecture, makes handling dates and times relatively straightforward. This article will guide you through different methods to calculate and work with local time in Node.js, focusing on various scenarios and using popular libraries for enhanced functionality.
Why Calculate Local Time?
- User Experience: Displaying times in the user's local time zone improves the user experience.
- Data Integrity: Ensures accurate time-based data logging and analysis.
- Global Applications: Supports applications that need to handle multiple time zones.
Basic Time Calculation with JavaScript
Node.js is built on JavaScript, and JavaScript provides built-in support for handling dates and times via the Date
object.
The approaches to Calculate Local Time in Node.js are:
Installation Steps
Step 1: Make a folder structure for the project.
mkdir myapp
Step 2:Â Navigate to the project directory
cd myapp
Step 3: Initialize the NodeJs project inside the myapp folder.
npm init -y
Project Structure:
Method 1: Using built-in methods
The built-in methods are provided by JavaScript. First, create a new Date object using the new Date() method and then use the same object to get the date part using toDateString() and the time part using toTimeString() methods.
Example: This example shows the use of a built-in javascript method to calculate local time in Node.js.
Node
// app.js
// Creating a Date object
const dateObj = new Date();
// Printing the date and time parts
console.log(`Date: ${dateObj.toDateString()}`);
console.log(`Time: ${dateObj.toTimeString()}`);
Step to Run Application:Â Run the application using the following command from the root directory of the project
node app.js
OutputDate: Tue Jul 02 2024
Time: 06:23:31 GMT+0000 (Coordinated Universal Time)
Method 2: Using luxon library
Luxon is a wrapper for JavaScript dates and times. First, we need to install luxon as a dependency in the project. To do so, run the following command from the root directory of the project.
npm install luxon
The updated dependencies in package.json file will look like:
"dependencies": {
"luxon": "^3.4.4",
}
Example: This example shows the use of luxon linbrary to calculate local time in Node.js.
Node
// app.js
const{ DateTime } = require('luxon');
// Creating a date time object
let date = DateTime.local();
// Printing the date and time parts
console.log(`Date: ${date.toLocaleString(DateTime.DATE_FULL)}`);
console.log(`Time: ${date.toLocaleString(DateTime.TIME_24_WITH_LONG_OFFSET)}`);
Step to Run Application:Â Run the application using the following command from the root directory of the project
node app.js
Output:
Date: November 11, 2020
Time: 18:57:20 India Standard Time