How to calculate local time in Node.js?


In this article, you will understand how to calculate local time in Node.js. The Date object works with dates and times. Date objects are created with new Date(). JavaScript will use the browser's time zone and display a date as a full text string.

Node.js is an open-source and cross-platform JavaScript runtime environment.As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications.

Example 1

In this example, we use the toDateString and toTimeString function

const dateTimeObject = new Date();
console.log("A date-time object is created
") console.log(`Date: ${dateTimeObject.toDateString()}`); console.log(`Time: ${dateTimeObject.toTimeString()}`);

Output

A date-time object is created

Date: Tue Jan 03 2023
Time: 11:27:40 GMT+0530 (India Standard Time)

Explanation

  • Step 1 − Define a date time object.

  • Step 2 − Display the date by using the toDateString() method.

  • Step 3 − Display the time by using the toTimeString() method.

Example 2

In this example, fetch the year, month etc separately using functions like getDate(), getMonth.

let dateObject = new Date();
console.log("A date object is defined")

let date = ("0" + dateObject.getDate()).slice(-2);
let month = ("0" + (dateObject.getMonth() + 1)).slice(-2);
let year = dateObject.getFullYear();

let hours = dateObject.getHours();
let minutes = dateObject.getMinutes();
let seconds = dateObject.getSeconds();

console.log("\displaying date and time in yyyy-mm-dd format")

console.log(year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds);

Output

A date object is defined
displaying date and time in yyyy-mm-dd format
2023-01-03 11:34:44

Explanation

  • Step 1 − Define a date time object.

  • Step 2 − Get the year, month and date value with getDate, getMonth and getFullYear methods respectively.

  • Step 3 − Get the hours, minutes and seconds values with getHours, getMinutes and getSeconds methods respectively.

Updated on: 16-Feb-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements