Categories
JavaScript Answers

How to format datetime in JavaScript?

Spread the love

Sometimes, we want to format datetime in JavaScript.

In this article, we’ll look at how to format datetime in JavaScript.

How to format datetime in JavaScript?

To format datetime in JavaScript, we can use the moment.js’ format method.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

to add the moment script.

Then we write:

const s = moment("2022-01-17T08:44:29+0100").format('MM/DD/YYYY');
console.log(s)

to call moment with a datetime string to create a moment object.

Then we call format on it with a format string to format it in the format specified.

Therefore, s is '01/16/2022'.

Conclusion

To format datetime in JavaScript, we can use the moment.js’ format method.

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 *