Format JavaScript date as yyyy-mm-dd
Related: 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.
52 Answers 52
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]
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.
const offset = yourDate.getTimezoneOffset(); yourDate = new Date(yourDate.getTime() + (offset*60*1000)); yourDate.toISOString().split(‘T’)[0] this should solve the issue of timezone
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
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 )
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'));
console.log(formatDate('Sun May 11,2014'));
@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.
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.
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.
I use this way to get the date in format yyyy-mm-dd 🙂
var todayDate = new Date().toISOString().slice(0, 10); console.log(todayDate);
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.
UTC. in australia we are +10 timezone. Because I tend to fix things in afternoon it has taken me a week to find this.
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).
const testCases = [ new Date().toLocaleDateString(), // 8/19/2020 new Date().toLocaleString(undefined, ), // 'Wednesday, 14/06/2023, 13:43:57' new Date().toLocaleDateString('en-US', ), // 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", ), // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone) new Date().toLocaleString("en-US", ), // 09 (just the hour) ] for (const testData of testCases)
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.
@TimHobbs you can set the timezone you want eg: («timeZone: «America/New_York») and the date will be converted to that timezone.
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() .
@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() .
They changed the ‘en-CA’ format, so be careful with that github.com/nodejs/node/issues/45945 Other formats in general should be good, it’s not common at all the change.
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];
- 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.
@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.
@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 👍
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!
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.
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('-');
I like the solution the best — easy to read, and does not rely on toISOString() and the potential timezone pitfalls with using that function.
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 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.
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
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.
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);
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');
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 also provides easy date/time counting solution.
@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).
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?
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)); >>);