How to convert an ISO date to the date format yyyy-mm-dd?

How can I get a date having the format yyyy-mm-dd from an ISO 8601 date?

My  8601 date is

2013-03-10T02:00:00Z

How can I get the following?

2013-03-10

Solution 1:

Just crop the string:

var date = new Date("2013-03-10T02:00:00Z");
date.toISOString().substring(0, 10);

Or if you need only date out of string.

var strDate = "2013-03-10T02:00:00Z";
strDate.substring(0, 10);

Solution 2:

Try this

date = new Date('2013-03-10T02:00:00Z');
date.getFullYear()+'-' + (date.getMonth()+1) + '-'+date.getDate();//prints expected format.

Update:-

As pointed out in comments, I am updating the answer to print leading zeros for date and month if needed.

date = new Date('2013-08-03T02:00:00Z');
year = date.getFullYear();
month = date.getMonth()+1;
dt = date.getDate();

if (dt < 10) {
  dt = '0' + dt;
}
if (month < 10) {
  month = '0' + month;
}

console.log(year+'-' + month + '-'+dt);

Solution 3:

You could checkout Moment.js, Luxon, date-fns or Day.js for nice date manipulation.

Or just extract the first part of your ISO string, it already contains what you want. Here is an example by splitting on the T:

"2013-03-10T02:00:00Z".split("T")[0] // "2013-03-10"

And another example by extracting the 10 first characters:

"2013-03-10T02:00:00Z".substr(0, 10) // "2013-03-10"

Solution 4:

This is what I do to get date only:

let isoDate = "2013-03-10T02:00:00Z";

alert(isoDate.split("T")[0]);