How to convert an ISO date to the date format yyyy-mm-dd? [duplicate]
Asked Answered
B

28

219

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
Brewmaster answered 6/8, 2014 at 11:34 Comment(2)
date.split("T")[0] would doDrumstick
Beware date.split("T")[0]. The output may vary depending on the time portion of the Date. Ex: https://mcmap.net/q/118546/-how-to-convert-an-iso-date-to-the-date-format-yyyy-mm-dd-duplicateAnthracosis
O
168

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);
Oliy answered 6/8, 2014 at 11:38 Comment(7)
Note, I don't think this will print a leading zero for day or monthLeitmotiv
Agree with @Leitmotiv this doesn't answer the question because it removes leading 0 therefore doesn't meet the requirements of YYYY-MM-DD formatMarguerite
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.Esch
sir can you please tell me how to pass 2013 3 1 this format date in new Date(date)Ardelia
Instead of two IFs, you can simply use dt = dt.padStart(2, '0')); and month = month.padStart(2, '0'));Semitics
@Semitics 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.Piglet
@Esch In a lot of normal uses that answer gives the wrong result. In London, for example, with daylight saving: d = new Date("25-Aug-2023"); d.toISOString().substr(0,10) leads to 2023-08-24Remanent
U
252

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);
Underarm answered 14/2, 2016 at 14:54 Comment(8)
I think this is the easiest and most elegant solution from them all but is here any downfall for this?Photina
@Photina 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 en.wikipedia.org/wiki/Year_10,000_problem)Diffidence
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.Fanniefannin
@GuillaumeF. an important consideration but it does comply with OP's requirementsChipmunk
I can't fathom why the string should be parsed to a Date. The substring option seems to be the simplest answer.Abysmal
I was just looking for a simple answer for my particular problem so its a +1 from meEulaliaeulaliah
Simple and concise!Arnica
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.Cornered
O
168

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);
Oliy answered 6/8, 2014 at 11:38 Comment(7)
Note, I don't think this will print a leading zero for day or monthLeitmotiv
Agree with @Leitmotiv this doesn't answer the question because it removes leading 0 therefore doesn't meet the requirements of YYYY-MM-DD formatMarguerite
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.Esch
sir can you please tell me how to pass 2013 3 1 this format date in new Date(date)Ardelia
Instead of two IFs, you can simply use dt = dt.padStart(2, '0')); and month = month.padStart(2, '0'));Semitics
@Semitics 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.Piglet
@Esch In a lot of normal uses that answer gives the wrong result. In London, for example, with daylight saving: d = new Date("25-Aug-2023"); d.toISOString().substr(0,10) leads to 2023-08-24Remanent
F
105

You could checkout date-fns or Day.js for nice date manipulation, including formatting as YYYY-MM-DD.

Or just extract the first part of your ISO string, it already contains what you want:

"2013-03-10T02:00:00Z".slice(0, 10) // "2013-03-10"
"2013-03-10T02:00:00Z".split("T", 1)[0] // "2013-03-10"
Forsooth answered 6/8, 2014 at 11:41 Comment(0)
D
37

This is what I do to get date only:

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

alert(isoDate.split("T")[0]);
Drumstick answered 23/12, 2017 at 13:5 Comment(2)
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.Wellfixed
toISOString uses UTC, which will produce the wrong local date for the period of the local timezone offset from midnight. – RobGSemicentennial
P
28

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
Philodendron answered 10/2, 2019 at 23:44 Comment(0)
W
22

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"
Watereddown answered 23/7, 2016 at 21:46 Comment(5)
While this code snippet may solve the question, including an explanation 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!Insurmountable
moment is a pretty huge library to use just for formatting. Rather use date-fns which is much smaller in size and gives the same functionality.Hotpress
@Hozefa, then answer the OP question with your solution.Watereddown
I wish moment had some function like .toISODateString(), because it's very frequent case...Wigan
moment is deprecated. even moment.js recommend to use another time libs as alternative.momentjs.com/docs/#/-project-statusMucous
H
17

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.

Hotpress answered 22/9, 2017 at 23:30 Comment(2)
moment.js is no longer maintained momentjs.com/docs/#/-project-statusFiddlehead
Just a small correction on format argument: 'yyyy-MM-dd' according to date-fnsRadiolocation
K
13

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

function getISODate(date) {
    //return date.toLocaleDateString('fr-CA');
    return date.toLocaleDateString('sv-SE');
}
getISODate(new Date()); // '2022-03-24'

P.S. This used to work with in Canadian 'en-CA' locale, but now at least since Feb 2023 Firefox and Chromium v110+ use the US date format. It still works in Canadian 'fr-CA' locale. Not sure which one is more future-proof.

Kathiekathleen answered 24/3, 2022 at 19:6 Comment(0)
J
10

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"
Jurisprudent answered 14/1, 2020 at 22:29 Comment(1)
Using toLocaleDateString with a Canadian locale returns a date in ISO format. e.g. date.toLocaleDateString('en-ca').Kathiekathleen
T
8

Use:

new Date().toISOString().substring(0, 10);
Transience answered 13/1, 2017 at 7:2 Comment(0)
F
6

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

let date = new Date();
date = date.toISOString().slice(0,10);
Fathom answered 26/7, 2016 at 12:49 Comment(2)
I dont know why this is not getting more votes, it worked perfectly, and answered the question with minimal effortDusky
This solution fails to properly handle timezones and will lead to unexpected output in many cases.Trossachs
B
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

Belldame answered 23/6, 2021 at 17:29 Comment(2)
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'"Tearjerker
@Tearjerker you can replace en-EN with en-GB This SO link has a list of other locales and their short codesOpenminded
I
5

WARNING: Most of these answers are wrong.

That is because toISOString() always returns the UTC date, not local date. So, for example, if your UTC time is 0500 and your timezone is GMT-0800, the day returned by toISOString() will be the UTC day, which will be one day ahead of the local timezone day.

You need to first convert the date to the local date.

const date = new Date();
date.setTime(date.getTime() - date.getTimezoneOffset()*60*1000)

Now date.toISOString() will always return the proper date according to the local timezone.

But wait, there's more. If we are also using toTimeString() that will now be wrong because time is now local and toTimeString() assumes it is UTC and converts it. So we need to first extract toTimeString() as a variable before doing the conversion.

The Date() class in javascript is inconsistent because of this and should really be updated to avoid this confusion. The toISOString() and toTimeString() methods should both do the same default things with respect to timezone.

Insensible answered 11/1, 2023 at 18:40 Comment(2)
I think it should be date.getTime() + date.getTimezoneOffset() * 60 *1000 See developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Cantoris
If the timezone offset is positive, you want to add time to the timestamp, and if the offset is negative, you want to subtract time, so the minus sign in the original answer is correct, since the offset for GMT+1 would be -60, subtracting -60 (effectively adding 60) gets you back to where you want to be.Balancer
M
4

Pass your date in the date object:

var d = new Date('2013-03-10T02:00:00Z');
d.toLocaleDateString().replace(/\//g, '-');
Millwork answered 6/8, 2014 at 11:45 Comment(4)
toLocaleDateString() will give in "/" format. Not "-" format.Tman
You can use the above with a replace of "/" with "-". Not the most elegant though if toLocaleDateString ever changesMarguerite
The result of toLocaleDateString is not consistent for all users, so may well not produce the result required by the OP.Abysmal
Using toLocaleDateString with a Canadian locale returns a date in ISO format. e.g. date.toLocaleDateString('en-ca').Kathiekathleen
A
3

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)
Asdic answered 16/8, 2018 at 7:9 Comment(1)
toISOString uses UTC, which will produce the wrong local date for the period of the local timezone offset from midnight.Abysmal
B
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
Blanche answered 30/4, 2020 at 10:25 Comment(0)
P
3

If you have the timezone you can do:

const myDate = "2022-10-09T18:30:00.000Z"
const requestTimezone = "Asia/Calcutta";

const newDate = new Date(myDate).toLocaleString("en-CA", {
  dateStyle: "short",
  timeZone: requestTimezone,
});

console.log(newDate)
>> 2022-10-10 

Another outputs:

const myDate = "2022-10-02T21:00:00.000Z"
const requestTimezone = "Asia/Jerusalem";
>> 2022-10-03 

const myDate = "2022-09-28T04:00:00.000Z"
const requestTimezone = "America/New_York";
>> 2022-09-28
Pandemonium answered 28/9, 2022 at 18:10 Comment(0)
F
2

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"));
Far answered 27/6, 2017 at 18:58 Comment(0)
W
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;
Wellknown answered 10/11, 2016 at 5:51 Comment(0)
S
0

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
}
Schwitzer answered 13/7, 2017 at 17:56 Comment(0)
H
0

    var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
    alert(d.toLocaleDateString());
Headspring answered 18/8, 2018 at 5:22 Comment(1)
This isn't in ISO format.Sum
A
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');
});
Anthracosis answered 6/4, 2022 at 21:36 Comment(0)
D
0

You can also use a package like Luxon. With this you can parse the full ISO date (fromISO) and to with it what you want, for example output to a date only ISO (toISODate).

const isoDate = DateTime.fromISO('2013-03-10T02:00:00Z').toISODate() // 2013-03-10
Dyne answered 13/2 at 12:40 Comment(0)
C
-2

Simpler way to get Year Or Month

let isoDateTime = "2013-03-10T02:00:00Z";
console.log(isoDateTime.split("T")[0]); //2013-03-10

Using Split Method

console.log(isoDateTime.split("-")[0]); //2013
console.log(isoDateTime.split("-")[1]); //03
Collodion answered 21/10, 2022 at 12:48 Comment(0)
A
-2

Here is a short javascript code to convert ISO 8601 timestamp to a readable local date and time.

var myDate = new Date('2013-03-10T02:00:00Z').toString();
console.log(myDate);

Outputs: Sun Mar 10 2013 07:45:00 GMT+0545 (Nepal Time)

Aunt answered 11/6, 2023 at 8:3 Comment(1)
This isn't in ISO format.Sum
W
-2

A shorter version for @Mritunjay's Answer

let d = new Date()
 
mysql_date = d.toISOString().slice(0, 10);
mysql_date = d.getFullYear()+'-' +(d.getMonth()<9?'0':'') + (d.getMonth()+1) + '-'+ (d.getDate()<10?'0':'') + d.getDate();
Wynny answered 23/2 at 8:4 Comment(1)
A code-only answer is not high quality. While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please edit your answer to include explanation and link to relevant documentation.Albinaalbinism
S
-3

$moment(date).format("YYYY-MM-DD")

Stopping answered 6/3, 2023 at 14:32 Comment(0)
C
-7

Use the below code. It is useful for you.

let currentDate = new Date()
currentDate.toISOString()
Cliquish answered 3/5, 2018 at 7:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.