How format a date in JavaScript to YY-MM-DD
Dates are a recurring theme in most web applications. Whether your editing a form, sending data to an endpoint or trying to create the right timestamp, formatting your dates correctly is incredibly important. So, how do you change the format of a date to YY-MM-DD?
This can be achieved natively or with moment.js. To achieve this using standard JavaScript try the following:
var d = new Date(date); date = [d.getFullYear(), ('0' + (d.getMonth() + 1)).slice(-2), ('0' + d.getDate()).slice(-2) ].join('-');
Essentially, using JavaScript’s various native date methods, we can construct an array where each index has the correct date format to yy-mm-dd. Then we can utilize .join('-')
to combine each element of the array into a string with each element separated by a dash.Â
I like this method a lot as there isn’t too much bloat. Alternatively, moment.js is one of, if not the most popular date manipulation libraries for JavaScript.
It makes formatting very straightforward:
var todaysDate = new Date(); var dateString = moment(todaysDate).format("YYYY-MM-DD"); var dateStringWithTime = moment(todaysDate).format("YYYY-MM-DD HH");
Overall, there are many different ways in JavaScript to format dates correctly but these two options provide relative simplicity.