How to format date in JavaScript (Date(), moment.js)
In this article you will learn ways to format date in JavaScript using both native language resources and external libraries.

What’s up programmer, how are you? Let’s learn more about JavaScript and date formatting!
In JavaScript we don’t have a native way of printing dates in Portuguese, so we can resort to some features of the language itself as well as external ones
In my searches on the subject, I found a function that aims to format each part of the date, for that purpose the Date object offers us the pt-br format
And then, we rejoin these fractions into a string
See an example of this function:
function actualDate(){ let date = new Date(), day = data.getDate().toString().padStart(2, '0'), month = (data.getMonth()+1).toString().padStart(2, '0'), year = data.getFullYear(); return `${day}/${month}/${year}`; } console.log(actualDate());
We will then have the following output:
12/05/2020
Of course this will depend on your current date, but see that the function does what it promises
We can then make variations of it by modifying the parameters so that it will return us another date
For example, instead of instantiating to get the current date, passing an argument in milliseconds of the date we want to format in our language
Using the moment.js
Note: moment.js is now deprecated
Another approach would be to use this great lib, which has its only focus on formatting dates
Click here to access the documentation
Basically we pass a string, which will form the date we need
See an example of use:
moment().format('MMMM Do YYYY, h:mm:ss a');
Much easier, right? 😀
Conclusion
In this article we learned how to format date in JavaScript
We use a strand of the pure JavaScript language, creating a function and using the available methods
And then we learned moment.js, which is a lib that perfectly solves the problem of formatting dates.