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.
var datetime = new Date();
console.log(datetime );
2022-07-11T13:32:25.966Z
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);
11-7-2022
11-7-2022 15:57:29
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));
1657555889
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);
16:24, Mon Jul 11 2022
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 }));
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:
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