Node js Get Current Date Time Tutorial

Node js Get Current Date Time Tutorial

In Node.js, you can easily get the current date and time in various formats using the built-in Date object and the Intl.DateTimeFormat API. In this tutorial, I’ll show you how to retrieve the current date and time in different formats, such as ISO 8601, custom formats, and localized formats.

How to Get Current Date Time in Node js

Here are some methods to get the current date and time in various formats in node js:

  • Getting the Current Date and Time in ISO 8601 Format
  • Getting the Current Date and Time in a Custom Format
  • Getting the Current Date and Time in a Localized Format

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

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of 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 from a starting stage. As well as demo example.

Leave a Reply

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