Skip to content
Related Articles

Related Articles

How to calculate local time in node js ?
  • Last Updated : 18 Nov, 2020

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 new Date() method and then use the same object to get the date part using toDateString() and the time part using toTimeString() methods.

Filename: index.js

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.

Filename: index.js

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
My Personal Notes arrow_drop_up
Recommended Articles
Page :