Open In App

How to calculate local time in Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, a JavaScript file is given and the task at hand is to calculate the local time. The local time is determined by the system in question where we execute our file. Node.js will be used as a runtime. 

There are two approaches to this problem that are discussed below:

Approach 1: The first approach is to use the built-in methods 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 above-explained approach.

Javascript




// Creating a Date object
const dateObj = new Date();
  
// Printing the date and time parts
console.log(`Date: ${dateObj.toDateString()}`);
console.log(`Time: ${dateObj.toTimeString()}`);


Run the index.js file using the following command:

node index.js

Output:

Date: Wed Nov 11 2020
Time: 18:39:31 GMT+0530 (India Standard Time)

Approach 2: The next approach is based on using a third-party library named luxon. 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 above command will install luxon as a dependency and it will be available for use in the JavaScript file.

Example: This example shows the use of the above-explained approach.

Javascript




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)}`);


Run the index.js file using the following command:

node index.js

Output:

Date: November 11, 2020
Time: 18:57:20 India Standard Time

Last Updated : 16 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads