179

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
Flip
  • 5,443
  • 6
  • 39
  • 69
Neeraj
  • 8,005
  • 17
  • 58
  • 84
  • 2
    Have you actually tried to do it? This is not a new question it has been answered multiple times. – bPratik Aug 06 '14 at 11:38
  • 1
    possible duplicate of [Where can I find documentation on formatting a date in JavaScript](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – bPratik Aug 06 '14 at 11:40
  • 30
    `date.split("T")[0]` would do – Aravindh Gopi Dec 23 '17 at 13:06
  • Beware `date.split("T")[0]`. The output may vary depending on the time portion of the Date. Ex: https://stackoverflow.com/a/71773898/101095 – Cuga Apr 07 '22 at 15:19

21 Answers21

211

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);
Captain Sparrow
  • 1,064
  • 15
  • 25
DriveByPoster
  • 2,159
  • 2
  • 8
  • 2
  • 3
    I think this is the easiest and most elegant solution from them all but is here any downfall for this? – Aida_Aida Mar 14 '17 at 11:04
  • 53
    @Aida_Aida The only issue I can think of is that if your code deals with geoloical-scale time at least 8000 years in the future, your code could break because the format will be `YYYYY-MM-DD` in the year 10000. To avoid this you could split on the `T` character instead. (See https://en.wikipedia.org/wiki/Year_10,000_problem) – apsillers Oct 12 '17 at 14:01
  • 22
    This way won't handle timezones correctly since the ISOString is UTC but the Date object is local. You have to take this in consideration. – Guillaume F. Apr 04 '19 at 10:45
  • 4
    @GuillaumeF. an important consideration but it does comply with OP's requirements – jamesjansson Sep 06 '19 at 06:56
  • I can't fathom why the string should be parsed to a Date. The *substring* option seems to be the simplest answer. – RobG Sep 10 '19 at 11:51
  • I was just looking for a simple answer for my particular problem so its a +1 from me – markc Jan 29 '20 at 13:00
  • Simple and concise! – kingisaac95 Jul 31 '20 at 11:32
  • The first option does handle time zones since ISO String is in UTC and `new Date` will convert the string to your time zone. To prove it, paste this in the console `utc= new Date("2022-04-01T23:59:00Z")` (or T00:00:01Z, depending on your zone) and, unless you are in UTC, the outcome will be a different day. – daniel p Apr 01 '22 at 04:10
148

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);
Mritunjay
  • 24,184
  • 7
  • 51
  • 67
  • 20
    Note, I don't think this will print a leading zero for day or month – user3413723 Jan 23 '15 at 07:14
  • 3
    Agree with @user3413723 this doesn't answer the question because it removes leading 0 therefore doesn't meet the requirements of YYYY-MM-DD format – James Murphy Apr 01 '15 at 09:14
  • Working fine @Mritunjay – Ravi Delixan Apr 20 '15 at 11:20
  • This is longer and more typo-prone compared to the answer by DriveByPoster. But I'll not give a downvote because it is more language-agnostic. It just doesn't use the simple tools at our disposal. – RoboticRenaissance Mar 01 '19 at 17:43
  • sir can you please tell me how to pass 2013 3 1 this format date in new Date(date) – Kapil Soni Jul 23 '20 at 07:07
  • 3
    Instead of two IFs, you can simply use `dt = dt.padStart(2, '0'));` and `month = month.padStart(2, '0'));` – Avatar Jan 25 '21 at 15:33
  • 1
    @Avatar close, but that won't work. your variables are numbers, so they don't have `padStart` function. You must use `.toString()` first. Either way, yes, I'd also use `padStart` turning it into nice oneliner :) Not like it can't be turned into oneliner while operating on integers. – Soul Reaver May 10 '21 at 11:56
86

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"
antoine129
  • 5,048
  • 4
  • 33
  • 54
29

This is what I do to get date only:

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

alert(isoDate.split("T")[0]);
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Aravindh Gopi
  • 1,984
  • 24
  • 35
  • 3
    This is the first answer to actually propose the split() idea as answer answer as far as I can tell and I like that solution for the effort vs reliability vs effectively factor though I use moment() everywhere I can though. – rainabba May 25 '18 at 22:00
  • 2
    toISOString uses UTC, which will produce the wrong local date for the period of the local timezone offset from midnight. – RobG – Michael Dimmitt Feb 13 '20 at 15:16
22

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
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Ammar H Alshaar
  • 237
  • 2
  • 4
19

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"
Elijah
  • 7,883
  • 2
  • 53
  • 49
  • 2
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations! – Blue Jul 23 '16 at 22:26
  • 4
    `moment` is a pretty huge library to use just for formatting. Rather use [date-fns](https://date-fns.org/v1.28.5/docs/format) which is much smaller in size and gives the same functionality. – Hozefa Sep 21 '17 at 23:27
  • @Hozefa, then answer the OP question with your solution. – Elijah Sep 22 '17 at 02:24
  • 1
    @Harris - did the job smoothly! – Ali Celebi Dec 07 '18 at 13:51
  • I wish moment had some function like `.toISODateString()`, because it's very frequent case... – Lev Lukomsky Dec 13 '18 at 15:22
  • moment is deprecated. even moment.js recommend to use another time libs as alternative.https://momentjs.com/docs/#/-project-status/ – Logan Lee Apr 04 '21 at 17:36
15

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.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Hozefa
  • 1,618
  • 6
  • 22
  • 34
9

Use:

new Date().toISOString().substring(0, 10);
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Ankita
  • 283
  • 4
  • 16
9

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"
Jook
  • 4,484
  • 3
  • 25
  • 50
6

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

let date = new Date();
date = date.toISOString().slice(0,10);
sebhs
  • 115
  • 1
  • 4
  • I dont know why this is not getting more votes, it worked perfectly, and answered the question with minimal effort – Wolfiebae Jul 02 '20 at 02:36
  • 1
    This solution fails to properly handle timezones and will lead to unexpected output in many cases. – inopinatus Feb 05 '21 at 07:45
6

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

  • nice solution but mainly for amercian's i'm afraid us brits get '3/10/2013' "new Date('2013-03-10T02:00:00Z').toLocaleDateString('en-EN', {year: 'numeric', month: 'numeric', day: 'numeric' }) === '3/10/2013'" – aqm Oct 15 '21 at 07:54
  • 2
    @aqm you can replace `en-EN` with `en-GB` This [SO link](https://stackoverflow.com/questions/3191664/list-of-all-locales-and-their-short-codes) has a list of other locales and their short codes – BrunoElo Dec 04 '21 at 17:10
5

Pass your date in the date object:

var d = new Date('2013-03-10T02:00:00Z');
d.toLocaleDateString().replace(/\//g, '-');
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
rk rk
  • 306
  • 1
  • 8
4

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)
  • 1
    *toISOString* uses UTC, which will produce the wrong local date for the period of the local timezone offset from midnight. – RobG Sep 10 '19 at 11:48
3

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"));
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Airwavezx
  • 325
  • 1
  • 9
3

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
asiniy
  • 13,006
  • 7
  • 59
  • 135
3

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'

naturallyfoster
  • 289
  • 1
  • 3
  • 13
1

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/

Alan
  • 6,996
  • 2
  • 38
  • 60
0
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;
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
MemoryLeak
  • 353
  • 2
  • 7
  • 19
0

    var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
    alert(d.toLocaleDateString());
Suraj Rao
  • 28,850
  • 10
  • 94
  • 99
Abilash Raghu
  • 355
  • 3
  • 7
0

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');
});
Cuga
  • 17,301
  • 30
  • 108
  • 159
-4

Use the below code. It is useful for you.

let currentDate = new Date()
currentDate.toISOString()
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124