Getting Date and Time Format in Node.js Example

Sovary July 12, 2022 344
2 minutes read

Today we will demo how to get current date and time in Node.js with various format. By default, there no required to import modules which we can use built-in Javascript date object. In Node.js we can format current date time as DD-MM-YYYY hh:mm:ss, YYYY-MM-DD, or DD-MM-YYYY, etc.

So below example you will see how to get current date time in Node.js, get current timestamp in nodejs, format date in node.js, get current date dd-mm-yyyy, get time in node.js by current date.

Example #1 - Fetch current date

var datetime = new Date();
console.log(datetime );

Output #1

2022-07-11T13:32:25.966Z

 

Example #2 - Extract date object

This example to show how we extract each value and form in various format.

var datetime = new Date();
var day = datetime.getDate();
var month = datetime.getMonth() + 1;
var year = datetime.getFullYear();

var hours = datetime.getHours();
var minutes = datetime.getMinutes();
var seconds = datetime.getSeconds();

// format dd-mm-yyyy hh:mm:ss
var datetime_format = day + "-" + month + "-" + year + " " + hours + ":" + minutes + ":" + seconds;
// format dd-mm-yyyy
var date = day + "-" + month + "-" + year;

console.log(date);
console.log(datetime_format);

Output #2

11-7-2022
11-7-2022 15:57:29

 

 

Example #3 - Get Timestamp as Seconds

Using Date.now() funciton to get current timestamp in Node.js. The method will return as millseconds so we will convert the timestamp as seconds by divided by 1000.

var timestamp = Date.now();
// timestamp in seconds
console.log(Math.floor(timestamp/1000));

Output #3

1657555889

 

Example #4 - Convert Timestamp to Date

We will get current time and pass to Date object and toDateString() will return date value in english short name,

var timestamp = Date.now();
var d = new Date(timestamp);
date = d.getHours() + ":" + d.getMinutes() + ", " + d.toDateString();
console.log(date);

Output #4

16:24, Mon Jul 11 2022

 

 

Example #5 - Convert Time to 12 Hour

By default time in Node.js is 24 hours but we can convert to 12 hour by method toLocalString with custom object as example below

var time = new Date();
console.log(time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true }));

Output #5

4:24 PM

 Hope these example to get current datetime in Node.js will help you to complete your project. Have a nice day!

You might Also Like:

Javascript  Node.js 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him