Getting Date and Time Format in Node.js Example

Sovary July 12, 2022 539
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

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him