Working with dates in JavaScript has historically been a challenge.
You want to be able to format dates in a way that is easy to read and understand, and you want to be able to parse dates in a way that is easy to read and understand.
In this post, we'll learn how to format a date in one of the most popular formats, YYYY-MM-DD.
Formatting Dates to YYYY-MM-DD
To format a date in this format, let's start off with our Date object:
JAVASCRIPT
const date = newDate();
Now let's make use of the toISOString() method, which converts our date object into a string following the ISO 8601 standard.
JAVASCRIPT
const dateString = date.toISOString();
JAVASCRIPT
const date = newDate();
const string = date.toISOString();
This returns us a string in this format, if you're from the US:
BASH
YYY-MM-DDTHH:MM:SS.sssZ
Now, all we need to do is split the string by the T character, and take the first element in the array: