How to Get Current Date and Time in Node JS

How to Get Current Date and Time in Node JS

The easiest way to get the current date, month, year, hour, minute and second etc in node js is to use the built-in Date object and Intl.DateTimeFormat API.

How to Get Current Date Time in Node js

Here are some ways:

Getting the Current Date and Time in ISO 8601 Format

The ISO 8601 format is a widely accepted standard for representing date and time information. To get the current date and time in this format, you can use the toISOString() method of the Date object in node js:

const currentDate = new Date();
const iso8601FormattedDate = currentDate.toISOString();
console.log('ISO 8601 Format:', iso8601FormattedDate);

Getting the Current Date and Time in a Custom Format

To get the current date and time in node js with custom format, you can use the js toLocaleString() method with a custom format specifier. Here’s an example of formatting the date as “YYYY-MM-DD HH:mm:ss”:

const currentDate = new Date();
const options = {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
};
const customFormattedDate = currentDate.toLocaleString('en-US', options);
console.log('Custom Format:', customFormattedDate);

Getting the Current Date and Time in a Localized Format

To get the current date and time in node js with format that respects the user’s locale and language preferences, you can use the toLocaleString() method without specifying any options. This will use the default locale settings:

const currentDate = new Date();
const localizedFormattedDate = currentDate.toLocaleString();
console.log('Localized Format:', localizedFormattedDate);

Conclusion

In this tutorial, you learned how to get the current date and time in different formats using Node.js. You can use these methods to format date and time information according to your application’s requirements, whether it’s for logging, displaying to users, or any other purpose.

Recommended Tutorials

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *