How to Format Date as YYYY-MM-DD in React
Format date as YYYY-MM-DD in React
To format the date as YYYY-MM-DD :
- Convert the date to ISO format using the toISOString() method on the date object.
- Split the date using the split() method to split the date string from T.
const today = new Date().toISOString().split('T')[0];
console.log(today);
In the example, we first converted the date to ISO format using the toISOString() method.
The toISOString() method returns the date as an ISO string. For example: 2022–07–12T15:43:14.361Z
Then we split the ISO string from ‘T’.
The split method splits a string into an array of substrings. For example, [‘2022–07–12’, ‘15:43:14.361Z’]
So to get the date in YYYY-MM-DD format, we selected the first index of an array.
You can also create a reusable function.
const formatDate = (date = new Date()) => {
return new Date().toISOString().split('T')[0];
}
const today = formatDate();
const futureDate = formatDate(new Date('May 04, 2025'));
console.log(today); //👉 2022-07-12
console.log(futureDate);//👉 2025-05-04
We created the formatDate() function; it accepts the date as an optional parameter.
If we do not pass any date to the function, it will return the current date.
In conclusion, as you can see, by writing just one line of code, you can format a date as YYYY-MM-DD in React.
I hope you found this article useful.
Learn More:
How to Format a Date as YYYY-MM-DD hh:mm:ss in JavaScript
How to Format Date as YYYY-MM-DD in JavaScript
How to Format Date in JavaScript