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

JavascriptDate

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

This is what I do to get date only:

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

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

Solution 5 - Javascript

let isoDate = "2013-03-10T02:00:00Z";
var d = new Date(isoDate);
d.toLocaleDateString('en-GB'); // dd/mm/yyyy
d.toLocaleDateString('en-US'); // mm/dd/yyyy

Solution 6 - Javascript

Moment.js will handle date formatting for you. Here is how to include it via a JavaScript tag, and then an example of how to use Moment.js to format a date.

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

moment("2013-03-10T02:00:00Z").format("YYYY-MM-DD") // "2013-03-10"

Solution 7 - Javascript

Moment.js is pretty big library to use for a single use case. I recommend using date-fns instead. It offers basically the most functionality of Moment.js with a much smaller bundle size and many formatting options.

import format from 'date-fns/format'
format('2013-03-10T02:00:00Z', 'YYYY-MM-DD'); // 2013-03-10, YYYY-MM-dd for 2.x

One thing to note is that, since it's the ISO 8601 time format, the browser generally converts from UTC time to local timezone. Though this is simple use case where you can probably do '2013-03-10T02:00:00Z'.substring(0, 10);.

For more complex conversions date-fns is the way to go.

Solution 8 - Javascript

Use:

new Date().toISOString().substring(0, 10);

Solution 9 - Javascript

To all who are using split, slice and other string-based attempts to obtain the date, you might set yourself up for timezone related fails!

An ISO-String has Zulu-Timezone and a date according to this timezone, which means, it might use a date a day prior or later to the actual timezone, which you have to take into account in your transformation chain.

See this example:

const timeZoneRelatedDate = new Date(2020, 0, 14, 0, 0);

console.log(timeZoneRelatedDate.toLocaleDateString(
    'ja-JP', 
    {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }
).replace(/\//gi,'-'));

// RESULT: "2020-01-14"

console.log(timeZoneRelatedDate.toISOString());

// RESULT: "2020-01-13T23:00:00.000Z" (for me in UTC+1)

console.log(timeZoneRelatedDate.toISOString().slice(0,10));

// RESULT: "2020-01-13"

Solution 10 - Javascript

This will output the date in YYYY-MM-DD format:

let date = new Date();
date = date.toISOString().slice(0,10);

Solution 11 - Javascript

The best way to format is by using toLocaleDateString with options


    const options = {year: 'numeric', month: 'numeric', day: 'numeric' };
    const date = new Date('2013-03-10T02:00:00Z').toLocaleDateString('en-EN', options)

Check Date section for date options here https://www.w3schools.com/jsref/jsref_tolocalestring.asp

Solution 12 - Javascript

Pass your date in the date object:

var d = new Date('2013-03-10T02:00:00Z');
d.toLocaleDateString().replace(/\//g, '-');

Solution 13 - Javascript

If you have a date object:

let date = new Date()
let result = date.toISOString().split`T`[0]

console.log(result)

or

let date = new Date()
let result = date.toISOString().slice(0, 10)

console.log(result)

Solution 14 - Javascript

To extend on rk rk's solution: In case you want the format to include the time, you can add the toTimeString() to your string, and then strip the GMT part, as follows:

var d = new Date('2013-03-10T02:00:00Z');
var fd = d.toLocaleDateString() + ' ' + d.toTimeString().substring(0, d.toTimeString().indexOf("GMT"));

Solution 15 - Javascript

A better version of answer by @Hozefa.

If you have date-fns installed, you could use formatISO function

const date = new Date(2019, 0, 2)
import { formatISO } from 'date-fns'
formatISO(date, { representation: 'date' }) // '2019-01-02' string

Solution 16 - Javascript

Using toLocaleDateString with the Canadian locale returns a date in ISO format.

function getISODate(date) {
    return date.toLocaleDateString('en-ca');
}
getISODate(new Date()); // '2022-03-24'

Solution 17 - Javascript

I used this:

HTMLDatetoIsoDate(htmlDate){
  let year = Number(htmlDate.toString().substring(0, 4))
  let month = Number(htmlDate.toString().substring(5, 7))
  let day = Number(htmlDate.toString().substring(8, 10))
  return new Date(year, month - 1, day)
}

isoDateToHtmlDate(isoDate){
  let date = new Date(isoDate);
  let dtString = ''
  let monthString = ''
  if (date.getDate() < 10) {
    dtString = '0' + date.getDate();
  } else {
    dtString = String(date.getDate())
  }
  if (date.getMonth()+1 < 10) {
    monthString = '0' + Number(date.getMonth()+1);
  } else {
    monthString = String(date.getMonth()+1);
  }
  return date.getFullYear()+'-' + monthString + '-'+dtString
}

Source: http://gooplus.fr/en/2017/07/13/angular2-typescript-isodate-to-html-date/

Solution 18 - Javascript

let dt = new Date('2013-03-10T02:00:00Z');
let dd = dt.getDate();
let mm = dt.getMonth() + 1;
let yyyy = dt.getFullYear();

if (dd<10) {
    dd = '0' + dd;
}
if (mm<10) {
    mm = '0' + mm;
}
return yyyy + '-' + mm + '-' + dd;

Solution 19 - Javascript

    var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
    alert(d.toLocaleDateString());

Solution 20 - Javascript

Many of these answers give potentially misleading output if one is looking for the day in the current timezone.

This function will output the day corresponding with the date's timezone offset:

const adjustDateToLocalTimeZoneDayString = (date?: Date) => {
    if (!date) {
        return undefined;
    }
    const dateCopy = new Date(date);
    dateCopy.setTime(dateCopy.getTime() - dateCopy.getTimezoneOffset()*60*1000);
    return dateCopy.toISOString().split('T')[0];
};

Tests:

it('return correct day even if timezone is included', () => {
    // assuming the test is running in EDT timezone
    // 11:34pm eastern time would be the next day in GMT
    let result = adjustDateToLocalTimeZoneDayString(new Date('Wed Apr 06 2022 23:34:17 GMT-0400'));
    // Note: This is probably what a person wants, the date in the current timezone
    expect(result).toEqual('2022-04-06');

    // 11:34pm zulu time should be the same
    result = adjustDateToLocalTimeZoneDayString(new Date('Wed Apr 06 2022 23:34:17 GMT-0000'));
    expect(result).toEqual('2022-04-06');

    result = adjustDateToLocalTimeZoneDayString(undefined);
    expect(result).toBeUndefined();
});

Misleading approach:

To demonstrate the issue with the other answers' direct ISOString().split() approach, note how the output below differs from what one might expect:

it('demonstrates how the simple ISOString().split() may be misleading', () => {
    // Note this is the 7th 
    expect(new Date('Wed Apr 06 2022 23:34:17 GMT-0400').toISOString().split('T')[0]).toEqual('2022-04-07');
});

Solution 21 - Javascript

Use the below code. It is useful for you.

let currentDate = new Date()
currentDate.toISOString()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNeerajView Question on Stackoverflow
Solution 1 - JavascriptDriveByPosterView Answer on Stackoverflow
Solution 2 - JavascriptMritunjayView Answer on Stackoverflow
Solution 3 - Javascriptantoine129View Answer on Stackoverflow
Solution 4 - JavascriptAravindh GopiView Answer on Stackoverflow
Solution 5 - JavascriptAmmar H AlshaarView Answer on Stackoverflow
Solution 6 - JavascriptElijahView Answer on Stackoverflow
Solution 7 - JavascriptHozefaView Answer on Stackoverflow
Solution 8 - JavascriptAnkitaView Answer on Stackoverflow
Solution 9 - JavascriptJookView Answer on Stackoverflow
Solution 10 - JavascriptsebhsView Answer on Stackoverflow
Solution 11 - JavascriptMANISH PARGANIHAView Answer on Stackoverflow
Solution 12 - Javascriptrk rkView Answer on Stackoverflow
Solution 13 - JavascriptИлья ЗеленькоView Answer on Stackoverflow
Solution 14 - JavascriptAirwavezxView Answer on Stackoverflow
Solution 15 - JavascriptasiniyView Answer on Stackoverflow
Solution 16 - JavascriptnaturallyfosterView Answer on Stackoverflow
Solution 17 - JavascriptAlanView Answer on Stackoverflow
Solution 18 - JavascriptMemoryLeakView Answer on Stackoverflow
Solution 19 - JavascriptAbilash RaghuView Answer on Stackoverflow
Solution 20 - JavascriptCugaView Answer on Stackoverflow
Solution 21 - JavascriptMohammad BilalView Answer on Stackoverflow