Categories
JavaScript Answers

How to format current time with JavaScript?

Spread the love

Sometimes, we want to format current time with JavaScript.

In this article, we’ll look at how to format current time with JavaScript.

How to format current time with JavaScript?

To format current time with JavaScript, we call toLocaleString, toLocaleDateString or toLocaleTimeString.

For instance, we write

const d = new Date();
console.log(d.toLocaleString());
console.log(d.toLocaleDateString());
console.log(d.toLocaleTimeString());

to create date d with the current datetime.

And then we call toLocaleString to return a string with the human readable locale datetime string with date and time being the values in d.

We call toLocaleDateString to return a string with the human readable locale date string with date and time being the values in d.

And we call toLocaleTimeString to return a string with the human readable locale time string with date and time being the values in d.

Conclusion

To format current time with JavaScript, we call toLocaleString, toLocaleDateString or toLocaleTimeString.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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