1113

I have a date with the format Sun May 11,2014. How can I convert it to 2014-05-11 using JavaScript?

function taskDate(dateMilli) {
    var d = (new Date(dateMilli) + '').split(' ');
    d[2] = d[2] + ',';

    return [d[0], d[1], d[2], d[3]].join(' ');
}

var datemilli = Date.parse('Sun May 11,2014');
console.log(taskDate(datemilli));

The code above gives me the same date format, sun may 11,2014. How can I fix this?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
user3625547
  • 11,159
  • 3
  • 12
  • 6
  • Really consider using a library like Moment.js. It will format in desired result :) – Ankur Jan 28 '16 at 19:14
  • 14
    Why using a library when 5 line of code can do the work ? @Ankur – Black Mamba May 15 '17 at 07:15
  • Possible duplicate of [Where can I find documentation on formatting a date in JavaScript?](https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – Heretic Monkey Jul 11 '18 at 18:08
  • Related: [What are valid Date Time Strings in JavaScript?](https://stackoverflow.com/questions/51715259/what-are-valid-date-time-strings-in-javascript/) Note that "Sun May 11,2014" is not a valid date string and parsing it might fail in some browsers. – str Feb 09 '19 at 12:33
  • @Black Mamba why use library when few line do trick – Maxim Therrien Jul 20 '22 at 15:44
  • Similar format `2/21/22, 7:45 AM`: `date.toLocaleString([], { dateStyle: 'short', timeStyle: 'short' })` ref.: https://stackoverflow.com/a/71210314/10018427 – Alex Szücs Nov 21 '22 at 15:56

53 Answers53

1446

Just leverage the built-in toISOString method that brings your date to the ISO 8601 format:

let yourDate = new Date()
yourDate.toISOString().split('T')[0]

Where yourDate is your date object.

Edit: @exbuddha wrote this to handle time zone in the comments:

const offset = yourDate.getTimezoneOffset()
yourDate = new Date(yourDate.getTime() - (offset*60*1000))
return yourDate.toISOString().split('T')[0]
Lindauson
  • 2,963
  • 1
  • 30
  • 33
Darth Egregious
  • 18,184
  • 3
  • 32
  • 54
  • 444
    BE CAREFUL with this method as it first converts to the date to UTC. If you are in a + timezone and your time portion is early in the day, then it could roll-back a day. Alternatively, if you're in a - timezone and your time portion is late in the day, then it could roll forward a day. – Luke Baulch Sep 13 '15 at 02:47
  • 20
    Try this instead: `new Date(yourDateStr).toISOString().split('T')[0]` – exbuddha Feb 12 '16 at 19:42
  • 53
    `const offset = yourDate.getTimezoneOffset(); yourDate = new Date(yourDate.getTime() + (offset*60*1000)); yourDate.toISOString().split('T')[0]` this should solve the issue of timezone – mjwrazor Feb 14 '18 at 17:11
  • 4
    How come this has 123 votes? My timezone is `+05:00` and `var yourDate = new Date(2018, 3 - 1, 26); yourDate.toISOString().split('T')[0];` gives me `"2018-03-25"`. – Salman A Mar 26 '18 at 18:19
  • 36
    `now.toISOString().substring(0,10);` This is a cleaner alternative, since it reminds you that `YYYY-MM-DD` are the first ten characters of the complete iso format – Gutimore Aug 26 '18 at 23:47
  • @SalmanA As Luke mentions, the date is converted in UTC when shown in ISO string (an ISO string is in UTC). The +5 being converted makes the day fall before midnight, as by default Date will be constructed at hour 00h00. – Félix Adriyel Gagnon-Grenier May 29 '19 at 12:38
  • @SalmanA I... see. That was not my impression of that comment, following the wonder upon the votes. I hope you did not feel condescended upon. – Félix Adriyel Gagnon-Grenier May 29 '19 at 20:57
  • If you use toISOString, it is easier if you encode your date using UTC in the first place: utcDate1 = new Date(Date.UTC(2020, 0, 1)) -> Wed Jan 01 2020 01:00:00 GMT+0100 (Central European Standard Time) utcDate1.toISOString()-> "2020-01-01T00:00:00.000Z" .Any date/datetime you encode using .UTC will map exactly back as you expect when using .toISOString() . – KenBuckley Mar 03 '20 at 08:32
  • 17
    Note: using the helpful solution commented by @mjwrazor, I had to subtract instead of add the offset to get the correct date (change the `+ (offset` to a `- (offset`) – rococo Mar 20 '20 at 02:10
  • 4
    @rococo you either add or subtract depending on your orientation from UTC 0. Which is England. – mjwrazor Mar 24 '20 at 14:37
  • @KenBuckley The question is how to get the date in YYYY-MM-DD format. Your comment _assumes_ that value is already available, so it doesn't apply here. – Tim Hobbs Jan 15 '21 at 01:19
  • Dirty, but it works ;) - @TimHobbs The `new Date()` construct allows generating the `Date` object – laconbass Apr 14 '21 at 17:04
  • 1
    Probably been said already but converting to ISO string and splitting it returns the wrong day for certain dates. Had something to do with timezones and day light savings time – a.anev Mar 18 '22 at 08:58
  • You can do this without the cludgy split by using [modern APIs, see this answer](https://stackoverflow.com/a/63490548/542251) – Liam Apr 27 '22 at 08:52
  • 2
    @rococo No, the timezoneoffset already has a sign, so you _always_ subtract – Auspex Nov 02 '22 at 11:18
  • Not sure if the spec has changed since this answer was written, but `toISOString()` puts it back into UTC time so it's not useful for other time zones: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString – Ben Sutton Jan 30 '23 at 18:13
963

You can do:

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;

    return [year, month, day].join('-');
}
 
console.log(formatDate('Sun May 11,2014'));

Usage example:

console.log(formatDate('Sun May 11,2014'));

Output:

2014-05-11

Demo on JSFiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/

Kos
  • 4,890
  • 9
  • 38
  • 42
user3470953
  • 11,025
  • 2
  • 17
  • 18
  • 38
    Really multiple variable declarations in the same statement? http://stackoverflow.com/questions/694102/declaring-multiple-variables-in-javascript – bhspencer Aug 29 '15 at 15:00
  • 30
    @Fuser97381 Multiple variable declarations in the same statement is more than just an aesthetic style preference. It is a dangerous practice. If you inadvertently fail add a comma after each declaration you end up creating global variables. Not something that should be encouraged on what may become the canonical answer to a question. – bhspencer Aug 31 '15 at 12:13
  • 18
    `'use strict';` @bhspencer – Vix Oct 20 '15 at 14:11
  • 5
    Reformatting a date string should not depend on successful parsing of non-standard strings by the built-in parser. Given the OP format, it can be reformatted in less code without using a Date at all. – RobG Jun 16 '17 at 12:12
  • How to increment more 30 days in range 1~31? – Steve Angello Feb 22 '19 at 16:19
  • What about doing the other way around: turn `2014-05-11` into `May 5, 2014`? – Razvan Zamfir Feb 25 '19 at 22:05
  • @RazvanZamfir check toLocaleDateString, it may be a cleaner way to output the format you seek: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString – Douglas Schmidt Sep 25 '19 at 20:25
  • 39
    this works like a charm but I don't understand why javascript does not have a native solution for this... I mean, we are in 2020 and date is an important aspect to web apps. – babaliaris Mar 04 '20 at 07:24
  • What I find interesting ist that, that this solution has two times better performance, than the one with `toISOString` – matvs May 14 '21 at 18:41
374

I use this way to get the date in format yyyy-mm-dd :)

var todayDate = new Date().toISOString().slice(0, 10);
console.log(todayDate);
Ruslan López
  • 4,433
  • 2
  • 26
  • 37
Mitch3091
  • 4,292
  • 3
  • 17
  • 23
  • 21
    How do you handle the date switching by a day as mentioned here by @Luke_Baulch? – Malvineous Sep 10 '16 at 13:45
  • 11
    You can do this: var todayDate = new Date(); todayDate.setMinutes(todayDate.getMinutes() - todayDate.getTimezoneOffset()); todayDate.toISOString().slice(0,10); This should help avoid the UTC problem. – Mitch3091 Sep 12 '16 at 15:44
  • 3
    @FernandoAguilar One doubt though, how do we know we need to subtract the offset or add it? – whyAto8 Apr 12 '17 at 10:40
  • `var todayDate = new Date(2018, 3 - 1, 26); todayDate.toISOString().slice(0, 10);` gives me `"2018-03-25"`. On another system `var todayDate = new Date(2018, 3 - 1, 26, 17, 0, 0); todayDate.toISOString().slice(0, 10);` gives me `"2018-03-27"`. – Salman A Mar 26 '18 at 18:22
  • 13
    Doesn't always work. It sometimes subtracts a day due to UTC conversion. – NickG May 22 '19 at 11:55
  • slicing strings is to bad practice – Даниил Пронин Oct 19 '20 at 07:38
  • 2
    UTC!!!! in australia we are +10 timezone. Because I tend to fix things in afternoon it has taken me a week to find this. – KenF Feb 25 '21 at 00:13
  • This will only work for the next ~8000 years. Should split on the T to be future proof – OneCricketeer Apr 21 '23 at 21:33
373

2020 ANSWER

You can use the native .toLocaleDateString() function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).

Examples

const testCases = [
  new Date().toLocaleDateString(), // 8/19/2020
  new Date().toLocaleString(undefined, {year: 'numeric', month: '2-digit', day: '2-digit', weekday:"long", hour: '2-digit', hour12: false, minute:'2-digit', second:'2-digit'}), // 'Wednesday, 14/06/2023, 13:43:57'
  new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}), // 08/19/2020 (month and day with two digits)
  new Date().toLocaleDateString('en-ZA'), // 2020/08/19 (year/month/day) notice the different locale
  new Date().toLocaleDateString('en-CA'), // 2020-08-19 (year-month-day) notice the different locale
  new Date().toLocaleString("en-US", {timeZone: "America/New_York"}), // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)
  new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}),  // 09 (just the hour)
]

for (const testData of testCases) {
  console.log(testData)
}

Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format. You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all

Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.

Zze
  • 18,229
  • 13
  • 85
  • 118
Juanma Menendez
  • 17,253
  • 7
  • 59
  • 56
  • This still suffers from problems with timezones as it is based off UTC, so you still have to jump all the hoops of determining the offset and altering the date. – Tim Hobbs Jan 15 '21 at 01:22
  • 1
    @TimHobbs you can set the timezone you want eg: ("timeZone: "America/New_York") and the date will be converted to that timezone. – Juanma Menendez Jan 15 '21 at 03:34
  • 13
    For my case where I didn't need the time zones, `new Date().toLocaleDateString('en-CA')` was perfect – Qarun Qadir Bissoondial Jan 19 '21 at 03:01
  • Can you format to `yyyy/mm/dd` in `toLocaleDateString()` ? – James Poulose Oct 13 '21 at 21:21
  • @JamesPoulose yes, you can do new Date().toLocaleDateString('en-ZA'); – Juanma Menendez Oct 14 '21 at 01:28
  • Exactly what I needed to get a particular format in local time. Thank you! – Ryan H. Jul 06 '22 at 12:49
  • Note that "locale" is a misnomer for language. The value for the *locale* parameter is a BCP47 language tag. I have no idea why ECMA-402 calls it locale, but it's just wrong. – RobG Sep 26 '22 at 20:34
  • 14
    The exact format of `.toLocaleDateString('en-CA')` is not portable and **will break in newer browsers**! It recently changed from `yyyy-MM-dd` to `M/d/yyyy` in browsers with ICU 72 (Chrome 110 and Firefox 110 beta). Do not make assumptions about specific the specific formatting of locales. Use one of the answers based on `.toISOString()`. – Anders Kaseorg Feb 12 '23 at 08:14
  • I switched from `en-CA` to `sv-SE` in 2023 due to to the issue @Anders mentioned. – Sam Barnum Feb 23 '23 at 20:39
  • 3
    @SamBarnum That…is the wrong lesson to learn here. There’s no guarantee `sv-SE` won’t change in the future too. If you’re parsing the result, use `.toISOString()`. – Anders Kaseorg Feb 23 '23 at 21:05
  • 2
    They changed the 'en-CA' format, so be careful with that https://github.com/nodejs/node/issues/45945 Other formats in general should be good, it's not common at all the change. – Juanma Menendez Feb 23 '23 at 22:30
  • I need the YYYY-MM-DD current date in the local time zone, not GMT time zone. I trust the `sv-SE` locale more than calculating the timezone offset. – Sam Barnum Feb 23 '23 at 22:54
  • 1
    Thank God they reverted it back. So can use en-CA again. https://unicode-org.atlassian.net/browse/CLDR-16399 – Rasul May 18 '23 at 18:33
  • 1
    This answer doesn't directly address the question. The gist here is essentially "try your luck with using a non-default locale"… and even then there is no explicit solution in the many (unrelated) examples given – Bin Ury Jun 19 '23 at 19:48
  • Even the hacky usage of the CA locale in the example outputs `yyyy/mm/dd` and the question asks for `yyyy-mm-dd` like an ISO date string. – Bin Ury Jun 19 '23 at 20:19
219

The simplest way to convert your date to the yyyy-mm-dd format, is to do this:

var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
                    .toISOString()
                    .split("T")[0];

How it works:

  • new Date("Sun May 11,2014") converts the string "Sun May 11,2014" to a date object that represents the time Sun May 11 2014 00:00:00 in a timezone based on current locale (host system settings)
  • new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )) converts your date to a date object that corresponds with the time Sun May 11 2014 00:00:00 in UTC (standard time) by subtracting the time zone offset
  • .toISOString() converts the date object to an ISO 8601 string 2014-05-11T00:00:00.000Z
  • .split("T") splits the string to array ["2014-05-11", "00:00:00.000Z"]
  • [0] takes the first element of that array

Demo

var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
                    .toISOString()
                    .split("T")[0];

console.log(dateString);

Note :

The first part of the code (new Date(...)) may need to be tweaked a bit if your input format is different from that of the OP. As mikeypie pointed out in the comments, if the date string is already in the expected output format and the local timezone is west of UTC, then new Date('2022-05-18') results in 2022-05-17. And a user's locale (eg. MM/DD/YYYY vs DD-MM-YYYY) may also impact how a date is parsed by new Date(...). So do some proper testing if you want to use this code for different input formats.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
  • 84
    No one else is aghast that this is the simplest way?? – gap Aug 27 '19 at 17:29
  • .toISOString() doesn't work correctly with daylight savings though. – Joe's Ideas Nov 25 '19 at 06:00
  • 2
    @JoeDevmon : I don't see how that's relevant here. The `- (date.getTimezoneOffset() * 60000 )` bit should eliminate any timezone differences, including the impact of daylight savings time. – John Slegers Nov 25 '19 at 09:42
  • 2
    @JohnSlegers that's what I was thinking, but then I was still getting the day before in some cases. I refactored and your example works now. I must have had a weird date string or something. Thanks for sticking with it and pointing that out. +1 – Joe's Ideas Nov 26 '19 at 01:09
  • 3
    I've searched high and low across SO and other sites to find the best way to deal with timezone issues with dates in JS, and hands down, this is by far the easiest and the best. Thank you! – HartleySan Mar 31 '20 at 13:44
  • 2
    It sad but it is simpliest way to format js date to string you need. I'm new in js, but in java it is 100 times easier to format date to any format. That is why was thinking there are easier way, but after I tried different solutions I choose this one. Thank you for your answer. – Юрий Яхница May 15 '20 at 10:52
  • The documentation for `.getTimezoneOffset()` says that it gives a positive value when the current locale is late from UTC, and a negative one when it's early. So shouldn't it be `new Date(date.getTime() + (date.getTimezoneOffset() * 60000 ))` instead to get the correct UTC DateTime? – jmpp Apr 06 '22 at 12:32
  • 1
    @jmpp : `date.getTime()` provides a date in a timezone based on your current locale. `date.getTimezoneOffset() * 60000 ` gives you the offset, in seconds of that same time zone, compared with the UTC time zone. By substracting the latter from the former, you effectively remove the offset from your date and thus get the correct date for the UTC time zone. – John Slegers Apr 09 '22 at 01:28
  • @JohnSlegers I missed that `date.getTime()` was also localized, so it makes sense now. Thank you! – jmpp Apr 13 '22 at 09:37
  • This fails in Chrome if the date string is already in the expected output format and the local timezone is west of UTC: `var date = new Date('2022-05-18')` results in '2022-05-17'. That means that if the user's locale format is not '5/18/2022' this might also break. This is because of the implementation of Date.parse: `new Date('2022-05-18')` is not equal to `new Date('5/18/2022')` – mikeypie May 20 '22 at 21:08
  • @mikeypie : I updated my answer and added your info as a note. – John Slegers Sep 30 '22 at 22:47
87

A combination of some of the answers:

var d = new Date(date);
date = [
  d.getFullYear(),
  ('0' + (d.getMonth() + 1)).slice(-2),
  ('0' + d.getDate()).slice(-2)
].join('-');
aqwsez
  • 1,487
  • 1
  • 12
  • 14
  • 3
    I like the solution the best - easy to read, and does not rely on `toISOString()` and the potential timezone pitfalls with using that function. – mfcallahan May 12 '19 at 16:59
  • 24
    this is the first one that doesn't make my brain hurt. – ckapilla Apr 12 '20 at 23:17
  • This fails in Chrome if the date string is already in the expected output format and the local timezone is west of UTC: `d = new Date('2022-05-18')` results in '2022-05-17'. That means that if the user's locale format is not '5/18/2022' this might also break. – mikeypie May 20 '22 at 21:04
  • 1
    @mikeypie Not true. You just simply got the date parsing wrong, since `new Date('2022-05-18')` will be parsed as UTC date `2022-05-18T00:00:00.000Z`, and this simply corresponds to a local time on `2022-05-17` if you're west of UTC. – emkey08 Dec 13 '22 at 07:18
62
format = function date2str(x, y) {
    var z = {
        M: x.getMonth() + 1,
        d: x.getDate(),
        h: x.getHours(),
        m: x.getMinutes(),
        s: x.getSeconds()
    };
    y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
        return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2)
    });

    return y.replace(/(y+)/g, function(v) {
        return x.getFullYear().toString().slice(-v.length)
    });
}

Result:

format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11
AJP
  • 26,547
  • 23
  • 88
  • 127
orangleliu
  • 752
  • 5
  • 6
  • 3
    I like the additional flexibility that this solution gives over the other answers to this question. I haven't thoroughly tested this, but for the format I desired (i.e. "yyyy-MM-dd hh:mm:ss"), it works just as expected. – porcus Mar 20 '15 at 02:37
  • 8
    You could eaaaaaaaasily avoid `eval`. – Salman A Mar 27 '18 at 07:59
  • 4
    here's a version which avoids the eval and comments better https://jsfiddle.net/8904cmLd/2/ – m1m1k Apr 05 '18 at 11:53
  • 4
    I benefited from this response. I did replace that line with the eval statement to `return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2);` – JesusIsMyDriver.dll Oct 10 '18 at 20:36
  • "H" should be capitalized, not "h" (small) – DavidDunham Mar 03 '21 at 08:06
61

If you don't have anything against using libraries, you could just use the Moments.js library like so:

var now = new Date();
var dateString = moment(now).format('YYYY-MM-DD');

var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nifemi Sola-Ojo
  • 851
  • 1
  • 9
  • 8
  • 4
    Cool solution, but its a 300kb package – Adam May 28 '20 at 13:55
  • Applied in react project: `npm install moment --save` `import moment from 'moment';` `const showEventDate = moment(your-date-here).format('YYYY-MM-DD; HH:mm A');` A pure solution for presenting date/time in any format. It gives local date-time with AM/PM and whatever you need just changing the format. [Moment.js](https://momentjs.com/) also provides easy date/time counting solution. – TradeCoder Dec 07 '20 at 06:59
  • @theTradeCoder as Adam mentioned above the size of moment is pretty large (I think it is more like 67kb, but still) so you should consider that when evaluating the ease of use and utility of any dependency. There are smaller alternatives (day.js = 2kb). – Tim Hobbs Jan 15 '21 at 01:27
  • 13
    Just an update about the `moment.js` library that - `moment.js` is already discontinued. – Rafik Farhad Mar 10 '21 at 13:10
50

You can use toLocaleDateString('fr-CA') on Date object

console.log(new Date('Sun May 11,2014').toLocaleDateString('fr-CA'));

Also I found out that those locales give right result from this locales list List of All Locales and Their Short Codes?

'en-CA'
'fr-CA'
'lt-LT'
'sv-FI'
'sv-SE'

var localesList = ["af-ZA",
  "am-ET",
  "ar-AE",
  "ar-BH",
  "ar-DZ",
  "ar-EG",
  "ar-IQ",
  "ar-JO",
  "ar-KW",
  "ar-LB",
  "ar-LY",
  "ar-MA",
  "arn-CL",
  "ar-OM",
  "ar-QA",
  "ar-SA",
  "ar-SY",
  "ar-TN",
  "ar-YE",
  "as-IN",
  "az-Cyrl-AZ",
  "az-Latn-AZ",
  "ba-RU",
  "be-BY",
  "bg-BG",
  "bn-BD",
  "bn-IN",
  "bo-CN",
  "br-FR",
  "bs-Cyrl-BA",
  "bs-Latn-BA",
  "ca-ES",
  "co-FR",
  "cs-CZ",
  "cy-GB",
  "da-DK",
  "de-AT",
  "de-CH",
  "de-DE",
  "de-LI",
  "de-LU",
  "dsb-DE",
  "dv-MV",
  "el-GR",
  "en-029",
  "en-AU",
  "en-BZ",
  "en-CA",
  "en-GB",
  "en-IE",
  "en-IN",
  "en-JM",
  "en-MY",
  "en-NZ",
  "en-PH",
  "en-SG",
  "en-TT",
  "en-US",
  "en-ZA",
  "en-ZW",
  "es-AR",
  "es-BO",
  "es-CL",
  "es-CO",
  "es-CR",
  "es-DO",
  "es-EC",
  "es-ES",
  "es-GT",
  "es-HN",
  "es-MX",
  "es-NI",
  "es-PA",
  "es-PE",
  "es-PR",
  "es-PY",
  "es-SV",
  "es-US",
  "es-UY",
  "es-VE",
  "et-EE",
  "eu-ES",
  "fa-IR",
  "fi-FI",
  "fil-PH",
  "fo-FO",
  "fr-BE",
  "fr-CA",
  "fr-CH",
  "fr-FR",
  "fr-LU",
  "fr-MC",
  "fy-NL",
  "ga-IE",
  "gd-GB",
  "gl-ES",
  "gsw-FR",
  "gu-IN",
  "ha-Latn-NG",
  "he-IL",
  "hi-IN",
  "hr-BA",
  "hr-HR",
  "hsb-DE",
  "hu-HU",
  "hy-AM",
  "id-ID",
  "ig-NG",
  "ii-CN",
  "is-IS",
  "it-CH",
  "it-IT",
  "iu-Cans-CA",
  "iu-Latn-CA",
  "ja-JP",
  "ka-GE",
  "kk-KZ",
  "kl-GL",
  "km-KH",
  "kn-IN",
  "kok-IN",
  "ko-KR",
  "ky-KG",
  "lb-LU",
  "lo-LA",
  "lt-LT",
  "lv-LV",
  "mi-NZ",
  "mk-MK",
  "ml-IN",
  "mn-MN",
  "mn-Mong-CN",
  "moh-CA",
  "mr-IN",
  "ms-BN",
  "ms-MY",
  "mt-MT",
  "nb-NO",
  "ne-NP",
  "nl-BE",
  "nl-NL",
  "nn-NO",
  "nso-ZA",
  "oc-FR",
  "or-IN",
  "pa-IN",
  "pl-PL",
  "prs-AF",
  "ps-AF",
  "pt-BR",
  "pt-PT",
  "qut-GT",
  "quz-BO",
  "quz-EC",
  "quz-PE",
  "rm-CH",
  "ro-RO",
  "ru-RU",
  "rw-RW",
  "sah-RU",
  "sa-IN",
  "se-FI",
  "se-NO",
  "se-SE",
  "si-LK",
  "sk-SK",
  "sl-SI",
  "sma-NO",
  "sma-SE",
  "smj-NO",
  "smj-SE",
  "smn-FI",
  "sms-FI",
  "sq-AL",
  "sr-Cyrl-BA",
  "sr-Cyrl-CS",
  "sr-Cyrl-ME",
  "sr-Cyrl-RS",
  "sr-Latn-BA",
  "sr-Latn-CS",
  "sr-Latn-ME",
  "sr-Latn-RS",
  "sv-FI",
  "sv-SE",
  "sw-KE",
  "syr-SY",
  "ta-IN",
  "te-IN",
  "tg-Cyrl-TJ",
  "th-TH",
  "tk-TM",
  "tn-ZA",
  "tr-TR",
  "tt-RU",
  "tzm-Latn-DZ",
  "ug-CN",
  "uk-UA",
  "ur-PK",
  "uz-Cyrl-UZ",
  "uz-Latn-UZ",
  "vi-VN",
  "wo-SN",
  "xh-ZA",
  "yo-NG",
  "zh-CN",
  "zh-HK",
  "zh-MO",
  "zh-SG",
  "zh-TW",
  "zu-ZA"
];

localesList.forEach(lcl => {
  if ("2014-05-11" === new Date('Sun May 11,2014').toLocaleDateString(lcl)) {
    console.log(lcl, new Date('Sun May 11,2014').toLocaleDateString(lcl));
  }
});
Aleksandr Belugin
  • 2,149
  • 1
  • 13
  • 19
  • Any idea _why_ this works? Is ISO format just the default, or do these locales genuinely use that format? If it's the former I'd be concerned that it could change unexpectedly in the future. – jymbob Feb 25 '20 at 11:13
  • THis is not working with NodeJS outside of browser. – Daniel Viglione Mar 25 '20 at 22:29
  • 2
    @jymbob I think these locales genuinely use those formats. I've came to the same answer by looking at this Wikipedia page: https://en.wikipedia.org/wiki/Date_format_by_country – Ciprian Tomoiagă Apr 17 '20 at 13:31
  • After 3 days, and trawling through too many SO javascript date questions, and trying to ask a new question (30 mins before closed as duplicate) here at last is an answer that is actually correct. I could weep. – Chris F Carroll Oct 09 '21 at 15:13
  • Thanks for these code, this is really a better shortcut to obtain format in js render. – Ansh Varun Jan 04 '22 at 12:10
  • `en-CA` no longer works in new Chrome – A. Rokinsky Feb 13 '23 at 11:33
25

The 2021 solution using Intl.

The new Intl Object is now supported on all browsers.
You can choose the format by choosing a "locale" that uses the required format.

The Swedish locale uses the format "yyyy-mm-dd":

// Create a date
const date = new Date(2021, 10, 28);

// Create a formatter using the "sv-SE" locale
const dateFormatter = Intl.DateTimeFormat('sv-SE');

// Use the formatter to format the date
console.log(dateFormatter.format(date)); // "2021-11-28"

Downsides of using Intl:

  • You cannot "unformat" or "parse" strings using this method
  • You have to search for the required format (for instance on Wikipedia) and cannot use a format-string like "yyyy-mm-dd"
Hendrik Jan
  • 4,396
  • 8
  • 39
  • 75
21

Simply use this:

var date = new Date('1970-01-01'); // Or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear());

Simple and sweet ;)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
21

Shortest

.toJSON().slice(0,10);

var d = new Date('Sun May 11,2014' +' UTC');   // Parse as UTC
let str = d.toJSON().slice(0,10);              // Show as UTC

console.log(str);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • 4
    This doesn't work when the client is ahead of the UTC and the date in the UTC time is one day behind the current client date. – Kunal Sep 08 '20 at 16:24
  • We don't need a screenshot for this if you are not in the 00+00 timezone: `> d=new Date() ; d.setHours(0,30,0,0) ; d` --> `Sat Oct 09 2021 00:30:00 GMT+0100 (BST)` ; `d.toJSON()` --> "2021-10-08T23:30:00.000Z" – Chris F Carroll Oct 09 '21 at 15:27
  • In snippet I show how to operate on UTC dates (which is timezone independent) – Kamil Kiełczewski Aug 27 '22 at 10:40
20

In the most of cases (no time zone handling) this is enough:

date.toISOString().substring(0,10)

Example

var date = new Date();
console.log(date.toISOString()); // 2022-07-04T07:14:08.925Z
console.log(date.toISOString().substring(0,10)); // 2022-07-04
Luca C.
  • 11,714
  • 1
  • 86
  • 77
19

toISOString() assumes your date is local time and converts it to UTC. You will get an incorrect date string.

The following method should return what you need.

Date.prototype.yyyymmdd = function() {         

    var yyyy = this.getFullYear().toString();                                    
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
    var dd  = this.getDate().toString();             

    return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

Source: https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1920925
  • 672
  • 6
  • 5
15

Retrieve year, month, and day, and then put them together. Straight, simple, and accurate.

function formatDate(date) {
    var year = date.getFullYear().toString();
    var month = (date.getMonth() + 101).toString().substring(1);
    var day = (date.getDate() + 100).toString().substring(1);
    return year + "-" + month + "-" + day;
}

//Usage example:
alert(formatDate(new Date()));
Luo Jiong Hui
  • 5,527
  • 2
  • 23
  • 18
15
new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );

or

new Date().toISOString().split('T')[0]
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString()
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString().split('T')[0]

Try this!

ctholho
  • 801
  • 11
  • 18
Williaan Lopes
  • 1,177
  • 15
  • 11
8

When ES2018 rolls around (works in chrome) you can simply regex it

(new Date())
    .toISOString()
    .replace(
        /^(?<year>\d+)-(?<month>\d+)-(?<day>\d+)T.*$/,
        '$<year>-$<month>-$<day>'
    )

2020-07-14

Or if you'd like something pretty versatile with no libraries whatsoever

(new Date())
    .toISOString()
    .match(
        /^(?<yyyy>\d\d(?<yy>\d\d))-(?<mm>0?(?<m>\d+))-(?<dd>0?(?<d>\d+))T(?<HH>0?(?<H>\d+)):(?<MM>0?(?<M>\d+)):(?<SSS>(?<SS>0?(?<S>\d+))\.\d+)(?<timezone>[A-Z][\dA-Z.-:]*)$/
    )
    .groups

Which results in extracting the following

{
    H: "8"
    HH: "08"
    M: "45"
    MM: "45"
    S: "42"
    SS: "42"
    SSS: "42.855"
    d: "14"
    dd: "14"
    m: "7"
    mm: "07"
    timezone: "Z"
    yy: "20"
    yyyy: "2020"
}

Which you can use like so with replace(..., '$<d>/$<m>/\'$<yy> @ $<H>:$<MM>') as at the top instead of .match(...).groups to get

14/7/'20 @ 8:45
Hashbrown
  • 12,091
  • 8
  • 72
  • 95
  • There are several simpler ways to butcher the `toISOString` string which were already posted before this one. For people who are willing to tolerate the potential inaccuracy of using `toISOString`, the sheer overhead and code bloat makes this a solution that no one should consider (the first snippet anyway). – mickmackusa Sep 18 '20 at 07:00
  • 3
    Look, man, unless you're trying to reparse dates literally [hundreds of thousands of times in a matter of seconds](https://measurethat.net/Benchmarks/Show/9652/0/i-suppose-you-think-we-should-write-in-assembly) you're not going to see *any difference at all*, so I don't know where you get off calling it bloat. Like with any other *novel* answer added to an old, already-answered question; this provides the reader with choice, and maybe, knowledge ("gee, I didnt know regex could do that!"). The reader should know whether or not an answer is appropriate for their usecase, and you insult them. – Hashbrown Sep 19 '20 at 05:13
  • I never mentioned performance so you can leave the argument about 100,000 iterations. My point is that earlier answers provided simpler techniques. – mickmackusa Sep 19 '20 at 05:17
  • 2
    Yes, but not readable, or easily extensible. You called it bloat, which is literally `code...that is perceived as unnecessarily long, slow, or otherwise wasteful of resources`. SO is primarily *for knowledge*, so yes, even though the literal question has been answered, sometimes there are other angles that others (and at least already literally `3▲`) find might useful! Imagine that. `I don't play the "Fastest Gun In The West" game, so when you see me post a late answer, it is because I have something valuable to offer and I hope that you will acknowledge the care that I take.` -some hypocrite – Hashbrown Sep 19 '20 at 05:22
  • 1
    Nothing hypocritical going on here. I am very clear about how the first snippet is far less attractive than simply calling `.slice(0,10)`. `slice()` is much more concise, direct, readable. I love regex but not for this question. See how I am not attacking you as a person? I am judging your answer to this question. – mickmackusa Sep 19 '20 at 07:20
  • I feel like the more important point is that all answers using toISOString or toJSON are just wrong for between 1 & 12 hours every day, for most of the world? – Chris F Carroll Oct 09 '21 at 15:37
  • I assume a lot of people are adjusting the Date by their utcOffset first. I could include that in the answer – Hashbrown Oct 10 '21 at 16:28
8
const formatDate = d => [
    d.getFullYear(),
    (d.getMonth() + 1).toString().padStart(2, '0'),
    d.getDate().toString().padStart(2, '0')
].join('-');

You can make use of padstart.

padStart(n, '0') ensures that a minimum of n characters are in a string and prepends it with '0's until that length is reached.

join('-') concatenates an array, adding '-' symbol between every elements.

getMonth() starts at 0 hence the +1.

Ado Ren
  • 3,511
  • 4
  • 21
  • 36
7

You can try this: https://www.npmjs.com/package/timesolver

npm i timesolver

Use it in your code:

const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, "YYYY-MM-DD");

You can get the date string by using this method:

getString
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sean1093
  • 109
  • 1
  • 3
7

To consider the timezone also, this one-liner should be good without any library:

new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
krsoni
  • 539
  • 7
  • 11
  • Problem with this is that every locale will return different result. For example ```en-GB``` will return ```20/12/2012``` and ```ko-KR``` will return```2012. 12. 20.```. But format should be ```yyyy-mm-dd``` – Gardelin Feb 10 '22 at 08:41
7

Unfortunately, JavaScript's Date object has many pitfalls. Any solution based on Date's builtin toISOString has to mess with the timezone, as discussed in some other answers to this question. The clean solution to represent an ISO-8601 date (without time) is given by Temporal.PlainDate from the Temporal proposal. As of February 2021, you have to choose the workaround that works best for you.

use Date with vanilla string concatenation

Assuming that your internal representation is based on Date, you can perform manual string concatenation. The following code avoids some of Date's pitfalls (timezone, zero-based month, missing 2-digit formatting), but there might be other issues.

function vanillaToDateOnlyIso8601() {
  // month May has zero-based index 4
  const date = new Date(2014, 4, 11);

  const yyyy = date.getFullYear();
  const mm = String(date.getMonth() + 1).padStart(2, "0"); // month is zero-based
  const dd = String(date.getDate()).padStart(2, "0");

  if (yyyy < 1583) {
    // TODO: decide how to support dates before 1583
    throw new Error(`dates before year 1583 are not supported`);
  }

  const formatted = `${yyyy}-${mm}-${dd}`;
  console.log("vanilla", formatted);
}

use Date with helper library (e.g. formatISO from date-fns)

This is a popular approach, but you are still forced to handle a calendar date as a Date, which represents

a single moment in time in a platform-independent format

The following code should get the job done, though:

import { formatISO } from "date-fns";

function dateFnsToDateOnlyIso8601() {
  // month May has zero-based index 4
  const date = new Date(2014, 4, 11);
  const formatted = formatISO(date, { representation: "date" });
  console.log("date-fns", formatted);
}

find a library that properly represents dates and times

I wish there was a clean and battle-tested library that brings its own well-designed date–time representations. A promising candidate for the task in this question was LocalDate from @js-joda/core, but the library is less active than, say, date-fns. When playing around with some example code, I also had some issues after adding the optional @js-joda/timezone.

However, the core functionality works and looks very clean to me:

import { LocalDate, Month } from "@js-joda/core";

function jodaDateOnlyIso8601() {
  const someDay = LocalDate.of(2014, Month.MAY, 11);
  const formatted = someDay.toString();
  console.log("joda", formatted);
}

experiment with the Temporal-proposal polyfill

This is not recommended for production, but you can import the future if you wish:

import { Temporal } from "proposal-temporal";

function temporalDateOnlyIso8601() {
  // yep, month is one-based here (as of Feb 2021)
  const plainDate = new Temporal.PlainDate(2014, 5, 11);
  const formatted = plainDate.toString();
  console.log("proposal-temporal", formatted);
}
Julius
  • 89
  • 1
  • 4
  • Note that the NPM package `proposal-temporal` is deprecated and should not be used. Developers looking for Temporal polyfills should check https://github.com/tc39/proposal-temporal#polyfills to see the recommended list of polyfills, which as of today are [`@js-temporal/polyfill`](https://www.npmjs.com/package/@js-temporal/polyfill) and [`temporal-polyfill`](https://www.npmjs.com/package/temporal-polyfill) – Justin Grant Jun 21 '22 at 22:20
6

I suggest using something like formatDate-js instead of trying to replicate it every time. Just use a library that supports all the major strftime actions.

new Date().format("%Y-%m-%d")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael Baldry
  • 1,990
  • 2
  • 14
  • 28
6

Simply Retrieve year, month, and day, and then put them together.

    function dateFormat(date) {
        const day = date.getDate();
        const month = date.getMonth() + 1;
        const year = date.getFullYear();

        return `${year}-${month}-${day}`;
    }

    console.log(dateFormat(new Date()));
5

Here is one way to do it:

var date = Date.parse('Sun May 11,2014');

function format(date) {
  date = new Date(date);

  var day = ('0' + date.getDate()).slice(-2);
  var month = ('0' + (date.getMonth() + 1)).slice(-2);
  var year = date.getFullYear();

  return year + '-' + month + '-' + day;
}

console.log(format(date));
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
5

Warning this code does not work in certain versions of Chrome, Node.js, etc.

  • Expected: yyyy-MM-dd
  • Actual: M/d/yyyy

References


Please consider timezones when converting Date to date string.

Two methods can be used.

  • .toISOString(); - Fixed to GMT+0. Includes time, which should be removed later.
  • .toLocaleDateString('en-CA'); - Timezone can be specified. Defaults to system.

Note that en-CA is a locale, not a timezone. Canada uses the YYYY-MM-DD format.

In the following example, the system timezone is set to PDT (GMT-7)

const date = new Date('2023-04-08 GMT+09:00');
// Sat Apr 08 2023 00:00:00 GMT+0900 (한국 표준시)
// Fri Apr 07 2023 08:00:00 GMT-0700 (Pacific Daylight Time)

// Based on GMT+0 or UTC - time is substringed.
date.toISOString(); // '2023-04-07T15:00:00.000Z'
date.toISOString().substring(0, 10); // '2023-04-07'

// Based on GMT-7 - local timezone of the system
date.toLocaleDateString('en-CA'); // '2023-04-07'

// Based on GMT+9 - Asia/Seoul is GMT+9
date.toLocaleDateString('en-CA', { timeZone: 'Asia/Seoul' }); // '2023-04-08'
Hyunbin
  • 423
  • 4
  • 6
4

Date.js is great for this.

require("datejs")
(new Date()).toString("yyyy-MM-dd")
Pang
  • 9,564
  • 146
  • 81
  • 122
Tan Wang
  • 811
  • 1
  • 6
  • 16
3

Yet another combination of the answers. Nicely readable, but a little lengthy.

function getCurrentDayTimestamp() {
  const d = new Date();

  return new Date(
    Date.UTC(
      d.getFullYear(),
      d.getMonth(),
      d.getDate(),
      d.getHours(),
      d.getMinutes(),
      d.getSeconds()
    )
  // `toIsoString` returns something like "2017-08-22T08:32:32.847Z"
  // and we want the first part ("2017-08-22")
  ).toISOString().slice(0, 10);
}
kadrian
  • 4,761
  • 8
  • 39
  • 61
  • Using your answer I created a nicely readable one line function. It accepts a javascript `Date` object as a parameter: `const formatDate = d => new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate())).toISOString().slice(0,10);` – ge333 Oct 13 '22 at 12:01
3

None of these answers quite satisfied me. I wanted a cross-platform solution that gave me the day in the local timezone without using any external libraries.

This is what I came up with:

function localDay(time) {
  var minutesOffset = time.getTimezoneOffset()
  var millisecondsOffset = minutesOffset*60*1000
  var local = new Date(time - millisecondsOffset)
  return local.toISOString().substr(0, 10)
}

That should return the day of the date, in YYYY-MM-DD format, in the timezone the date references.

So for example, localDay(new Date("2017-08-24T03:29:22.099Z")) will return "2017-08-23" even though it's already the 24th at UTC.

You'll need to polyfill Date.prototype.toISOString for it to work in Internet Explorer 8, but it should be supported everywhere else.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Erik Pukinskis
  • 480
  • 5
  • 11
  • Maybe worth noting that it will only give you 2017-08-23 if you're sufficiently behind UTC (e.g. in the US). – Simon D Sep 18 '17 at 08:40
3

A few of the previous answer were OK, but they weren't very flexible. I wanted something that could really handle more edge cases, so I took @orangleliu 's answer and expanded on it. https://jsfiddle.net/8904cmLd/1/

function DateToString(inDate, formatString) {
    // Written by m1m1k 2018-04-05

    // Validate that we're working with a date
    if(!isValidDate(inDate))
    {
        inDate = new Date(inDate);
    }

    // See the jsFiddle for extra code to be able to use DateToString('Sun May 11,2014', 'USA');
    //formatString = CountryCodeToDateFormat(formatString);

    var dateObject = {
        M: inDate.getMonth() + 1,
        d: inDate.getDate(),
        D: inDate.getDate(),
        h: inDate.getHours(),
        m: inDate.getMinutes(),
        s: inDate.getSeconds(),
        y: inDate.getFullYear(),
        Y: inDate.getFullYear()
    };

    // Build Regex Dynamically based on the list above.
    // It should end up with something like this: "/([Yy]+|M+|[Dd]+|h+|m+|s+)/g"
    var dateMatchRegex = joinObj(dateObject, "+|") + "+";
    var regEx = new RegExp(dateMatchRegex,"g");
    formatString = formatString.replace(regEx, function(formatToken) {
        var datePartValue = dateObject[formatToken.slice(-1)];
        var tokenLength = formatToken.length;

        // A conflict exists between specifying 'd' for no zero pad -> expand
        // to '10' and specifying yy for just two year digits '01' instead
        // of '2001'.  One expands, the other contracts.
        //
        // So Constrict Years but Expand All Else
        if (formatToken.indexOf('y') < 0 && formatToken.indexOf('Y') < 0)
        {
            // Expand single digit format token 'd' to
            // multi digit value '10' when needed
            var tokenLength = Math.max(formatToken.length, datePartValue.toString().length);
        }
        var zeroPad = (datePartValue.toString().length < formatToken.length ? "0".repeat(tokenLength) : "");
        return (zeroPad + datePartValue).slice(-tokenLength);
    });

    return formatString;
}

Example usage:

DateToString('Sun May 11,2014', 'MM/DD/yy');
DateToString('Sun May 11,2014', 'yyyy.MM.dd');
DateToString(new Date('Sun Dec 11,2014'),'yy-M-d');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
m1m1k
  • 1,375
  • 13
  • 14
  • Nice clean & commented solution. Yet I'm skeptical about the first argument, which is *silently* replaced by a fresh new date if not recognized as a valid date. I'd rather put this "optionnal default value" as 2nd argument instead, and return some kind of exception (could be a simple "Invalid date format" returned string) in case the format isn't recognized, so that error appear *clearly* to the tester/user – Balmipour Oct 16 '19 at 10:04
3

If you use momentjs, now they include a constant for that format YYYY-MM-DD:

date.format(moment.HTML5_FMT.DATE)
Stefan Zhelyazkov
  • 2,599
  • 4
  • 16
  • 41
3

I have a oneliner for this

dateInstance.toLocaleDateString().replaceAll("/", "-").split("-").reverse().join("-");
SagarKapasi099
  • 418
  • 6
  • 8
3

You can use this function for better format and easy of use:

function convert(date) {
    const d = Date.parse(date)
    const   date_obj = new Date(d)
    return `${date_obj.getFullYear()}-${date_obj.toLocaleString("default", { month: "2-digit" })}-${date_obj.toLocaleString("default", { day: "2-digit"})}`
}

This function will format the month as 2-digit output as well as the days

Amado Saladino
  • 2,114
  • 23
  • 25
2

Reformatting a date string is fairly straightforward, e.g.

var s = 'Sun May 11,2014';

function reformatDate(s) {
  function z(n){return ('0' + n).slice(-2)}
  var months = [,'jan','feb','mar','apr','may','jun',
                 'jul','aug','sep','oct','nov','dec'];
  var b = s.split(/\W+/);
  return b[3] + '-' +
    z(months.indexOf(b[1].substr(0,3).toLowerCase())) + '-' +
    z(b[2]);
}

console.log(reformatDate(s));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RobG
  • 142,382
  • 31
  • 172
  • 209
2

const YYYY_MM_DD_Formater = (date) => {
    const t = new Date(date)
    const y = t.getFullYear()
    const m = ('0' + (t.getMonth() + 1)).slice(-2)
    const d = ('0' + t.getDate()).slice(-2)
    return `${y}-${m}-${d}`
}

Update

const YYYY_MM_DD_Formater = (date,format='YYYY-MM-DD') => {
    const t = new Date(date)
    const y = t.getFullYear()
    const m = ('0' + (t.getMonth() + 1)).slice(-2)
    const d = ('0' + t.getDate()).slice(-2)
    return format.replace('YYYY',y).replace('MM',m).replace('DD',d)
}
m-zemmouri
  • 123
  • 8
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 04 '23 at 11:46
1

function myYmd(D){
    var pad = function(num) {
        var s = '0' + num;
        return s.substr(s.length - 2);
    }
    var Result = D.getFullYear() + '-' + pad((D.getMonth() + 1)) + '-' + pad(D.getDate());
    return Result;
}

var datemilli = new Date('Sun May 11,2014');
document.write(myYmd(datemilli));
Andrei
  • 882
  • 8
  • 13
1

This worked for me to get the current date in the desired format (YYYYMMDD HH:MM:SS):

var d = new Date();

var date1 = d.getFullYear() + '' +
            ((d.getMonth()+1) < 10 ? "0" + (d.getMonth() + 1) : (d.getMonth() + 1)) +
            '' +
            (d.getDate() < 10 ? "0" + d.getDate() : d.getDate());

var time1 = (d.getHours() < 10 ? "0" + d.getHours() : d.getHours()) +
            ':' +
            (d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes()) +
            ':' +
            (d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds());

print(date1+' '+time1);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SaP
  • 61
  • 1
  • 2
  • 10
1

var d = new Date("Sun May 1,2014");

var year  = d.getFullYear();
var month = d.getMonth() + 1;
var day   = d.getDate(); 

month = checkZero(month);             
day   = checkZero(day);

var date = "";

date += year;
date += "-";
date += month;
date += "-";
date += day;

document.querySelector("#display").innerHTML = date;
    
function checkZero(i) 
{
    if (i < 10) 
    {
        i = "0" + i
    };  // add zero in front of numbers < 10

    return i;
}
<div id="display"></div>
antelove
  • 3,216
  • 26
  • 20
1
new Date(new Date(YOUR_DATE.toISOString()).getTime() - 
                 (YOUR_DATE.getTimezoneOffset() * 60 * 1000)).toISOString().substr(0, 10)
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Lin
  • 497
  • 5
  • 15
1

No library is needed

Just pure JavaScript.

The example below gets the last two months from today:

var d = new Date()
d.setMonth(d.getMonth() - 2);
var dateString = new Date(d);
console.log('Before Format', dateString, 'After format', dateString.toISOString().slice(0,10))
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Panayiotis Georgiou
  • 1,135
  • 3
  • 19
  • 36
1

PHP compatible date format

Here is a small function which can take the same parameters as the PHP function date() and return a date/time string in JavaScript.

Note that not all date() format options from PHP are supported. You can extend the parts object to create the missing format-token

/**
 * Date formatter with PHP "date()"-compatible format syntax.
 */
const formatDate = (format, date) => {
  if (!format) { format = 'Y-m-d' }
  if (!date) { date = new Date() }

  const parts = {
    Y: date.getFullYear().toString(),
    y: ('00' + (date.getYear() - 100)).toString().slice(-2),
    m: ('0' + (date.getMonth() + 1)).toString().slice(-2),
    n: (date.getMonth() + 1).toString(),
    d: ('0' + date.getDate()).toString().slice(-2),
    j: date.getDate().toString(),
    H: ('0' + date.getHours()).toString().slice(-2),
    G: date.getHours().toString(),
    i: ('0' + date.getMinutes()).toString().slice(-2),
    s: ('0' + date.getSeconds()).toString().slice(-2)
  }

  const modifiers = Object.keys(parts).join('')
  const reDate = new RegExp('(?<!\\\\)[' + modifiers + ']', 'g')
  const reEscape = new RegExp('\\\\([' + modifiers + '])', 'g')

  return format
    .replace(reDate, $0 => parts[$0])
    .replace(reEscape, ($0, $1) => $1)
}

// ----- EXAMPLES -----
console.log( formatDate() ); // "2019-05-21"
console.log( formatDate('H:i:s') ); // "16:21:32"
console.log( formatDate('Y-m-d, o\\n H:i:s') ); // "2019-05-21, on 16:21:32"
console.log( formatDate('Y-m-d', new Date(2000000000000)) ); // "2033-05-18"

Gist

Here is a gist with an updated version of the formatDate() function and additional examples: https://gist.github.com/stracker-phil/c7b68ea0b1d5bbb97af0a6a3dc66e0d9

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Philipp
  • 10,240
  • 8
  • 59
  • 71
1

Use the new Temporal proposal (see browser support below) with a PlainDate object:

Temporal.PlainDate.from({ year: 2006, month: 8, day: 24 }).toString() // '2006-08-24'

Or, if you want the date for today:

Temporal.Now.plainDateISO().toString() // '2023-08-25'

Demo with <input type="date" /> (React): https://codesandbox.io/s/hungry-forest-nymhkl?file=/src/App.js

Browser Support

Temporal proposal on Can I use shows lacking support for now (no browsers supporting this as of Aug 2023). So unless this changes by the time you do this, you will need to install @js-temporal/polyfill and apply the polyfill like this:

import { Temporal, Intl, toTemporalInstant } from '@js-temporal/polyfill';
Date.prototype.toTemporalInstant = toTemporalInstant;
Karl Horky
  • 4,410
  • 2
  • 31
  • 35
0

If the date needs to be the same across all time zones, for example represents some value from the database, then be sure to use UTC versions of the day, month, fullyear functions on the JavaScript date object as this will display in UTC time and avoid off-by-one errors in certain time zones.

Even better, use the Moment.js date library for this sort of formatting.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
GameSalutes
  • 1,762
  • 2
  • 18
  • 24
0

Format and finding maximum and minimum date from hashmap data:

var obj = {"a":'2001-15-01', "b": '2001-12-02' , "c": '2001-1-03'};

function findMaxMinDate(obj){
  let formatEncode = (id)=> { let s = id.split('-'); return `${s[0]+'-'+s[2]+'-'+s[1]}`}
  let formatDecode = (id)=> { let s = id.split('/'); return `${s[2]+'-'+s[0]+'-'+s[1]}`}
  let arr = Object.keys( obj ).map(( key )=> { return new Date(formatEncode(obj[key])); });
  let min = new Date(Math.min.apply(null, arr)).toLocaleDateString();
  let max = new Date(Math.max.apply(null, arr)).toLocaleDateString();
  return {maxd: `${formatDecode(max)}`, mind:`${formatDecode(min)}`}
}

console.log(findMaxMinDate(obj));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
0

This code change the order of DD MM YYYY

function convertDate(format, date) {
    let formatArray = format.split('/');
    if (formatArray.length != 3) {
        console.error('Use a valid Date format');
        return;
    }
    function getType(type) { return type == 'DD' ? d.getDate() : type == 'MM' ? d.getMonth() + 1 : type == 'YYYY' && d.getFullYear(); }
    function pad(s) { return (s < 10) ? '0' + s : s; }
    var d = new Date(date);
    return [pad(getType(formatArray[0])), pad(getType(formatArray[1])), getType(formatArray[2])].join('/');
}
Black0ut
  • 1,642
  • 14
  • 28
0

const today = new Date(); // or whatever 

const yearFirstFormater = (date): string => {
    const modifiedDate = new Date(date).toISOString().slice(0, 10);
    return `${modifiedDate.split('-')[0]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}`;
}

const monthFirstFormater = (date): string => {
    const modifiedDate = new Date(date).toISOString().slice(0, 10);
    return `${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[0]}`;
}

const dayFirstFormater = (date): string => {
    const modifiedDate = new Date(date).toISOString().slice(0, 10);
    return `${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[0]}`;
}

console.log(yearFirstFormater(today));
console.log(monthFirstFormater(today));
console.log(dayFirstFormater(today));
Muhammed Moussa
  • 4,589
  • 33
  • 27
0
formatDate(date) {
  const d = new Date(date)
  const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
  const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
  const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
  return `${da}-${mo}-${ye}`;
}

console.log("Formatated Date : ", formatDate("09/25/2020") )
// Output :: Formatated Date : 25-Sep-2020
Tejas Savaliya
  • 572
  • 7
  • 8
0

Follow up on https://stackoverflow.com/a/29774197/1189762 This is what I had to change regarding the offset for when people are east or west from the Greenwich Mean Time:

export const toNativeHtml5InputDate = (date) => {
  if (!date) return date;

  let offset = new Date(date).getTimezoneOffset();

  offset =
    offset < 0
      ? offset * -1 // east from Greenwich Mean Time
      : offset; // west from Greenwich Mean Time

  return new Date(new Date(date).getTime() + offset * 60 * 1000)
    .toISOString()
    .split('T')[0];
};
Robin Wieruch
  • 14,900
  • 10
  • 82
  • 107
-1

All given answers are great and helped me big. In my situation, I wanted to get the current date in yyyy mm dd format along with date-1. Here is what worked for me.

var endDate = new Date().toISOString().slice(0, 10); // To get the Current Date in YYYY MM DD Format

var newstartDate = new Date();
newstartDate.setDate(newstartDate.getDate() - 1);
var startDate = newstartDate.toISOString().slice(0, 10); // To get the Yesterday's Date in YYYY MM DD Format
alert(startDate);
Pang
  • 9,564
  • 146
  • 81
  • 122
-1

I modified Samit Satpute's response as follows:

var newstartDate = new Date();
// newstartDate.setDate(newstartDate.getDate() - 1);
var startDate = newstartDate.toISOString().replace(/[-T:\.Z]/g, ""); //.slice(0, 10); // To get the Yesterday's Date in YYYY MM DD Format
console.log(startDate);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
suleman
  • 66
  • 6
-3

It is easily accomplished by my date-shortcode package:

const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYY-MM-DD}', 'Sun May 11,2014')
//=> '2014-05-11'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kodie Grantham
  • 1,963
  • 2
  • 17
  • 27
-6

We run constantly into problems like this. Every solution looks so individual. But looking at php, we have a way dealing with different formats. And there is a port of php's strtotime function at https://locutus.io/php/datetime/strtotime/. A small open source npm package from me as an alternative way:

<script type="module">
import { datebob } from "@dipser/datebob.js";
console.log( datebob('Sun May 11, 2014').format('Y-m-d') ); 
</script>

See datebob.js

dipser
  • 442
  • 3
  • 5
-6

Use joda-js and be done with it:

import { DateTimeFormatter, LocalDateTime } from 'js-joda'

const now = LocalDateTime.now()
now.format(DateTimeFormatter.ofPattern('yyyyMMdd-HH:mm:ss'))
// Outputs: 20221104-09:25:09 according to your timezone (mine is 'America/New_York'
Jose Quijada
  • 558
  • 6
  • 13
-8

This worked for me, and you can paste this directly into your HTML if needed for testing:

<script type="text/javascript">
    if (datefield.type!="date"){ // If the browser doesn't support input type="date",
                                 // initialize date picker widget:
        jQuery(function($){ // On document.ready
            $('#Date').datepicker({
                dateFormat: 'yy-mm-dd', // THIS IS THE IMPORTANT PART!!!
                showOtherMonths: true,
                selectOtherMonths: true,
                changeMonth: true,
                minDate: '2016-10-19',
                maxDate: '2016-11-03'
            });
        })
    }
</script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jason
  • 77
  • 1
  • 3
  • 9