Reputation: 12459
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?
Upvotes: 1243
Views: 3132773
Reputation: 180
One-liner with date and time:
date.toISOString().slice(0,19).replace("T"," ");
which gives this format: "2024-07-07 13:21:41"
Upvotes: 2
Reputation: 7372
Based on a few answers, I have concluded with two one-liner solutions to getting a formatted YYYY-MM-DD
date:
Local date:
new Date("2024-06-18T12:00").toLocaleDateString`en-CA` // 2024-06-18
Zulu date:
new Date("2024-06-18").toISOString().split`T`[0] // 2024-06-18 (or the date relative to your timezone at 0:00)
Depending on how you are getting your Date
object and your needs you would use one over the other. I added T12:00
because formatting the date with just 2024-06-18
is actually setting the date at 0:00 in Zulu time, therefore it may be different depending where you are. I'm in Hawaii (-10 offset), so the it displayed the day before, 2024-06-17
. T12:00
would keep mostly everyone on the same day.
Here's a snippet that shows a solution to OP's question.
const date = new Date(Date.parse('Sun May 11,2014'));
console.log(date.toLocaleDateString('en-CA')); // 2014-05-11
console.log(date.toISOString().split`T`[0]); // 2014-05-11
Upvotes: 0
Reputation: 1192
This is what I did.
Another alternate short and simple method:-
const date = new Date().toISOString();
console.log(date.substring(0, date.indexOf('T')));
Used substring()
with indexOf("T")
rather than splitting it into array at character 'T' and accessing element at 0th index.
Upvotes: 7
Reputation: 4944
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
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;
Upvotes: 5
Reputation: 20229
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.
Upvotes: 426
Reputation: 151
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)
}
Upvotes: 4
Reputation: 751
Warning this code does not work in certain versions of Chrome, Node.js, etc.
yyyy-MM-dd
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'
Upvotes: 6
Reputation: 1367
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!
Upvotes: 16
Reputation: 2692
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
Upvotes: 4
Reputation: 690
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'
Upvotes: -6
Reputation: 99
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()));
Upvotes: 8
Reputation: 47111
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 arrayvar date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
console.log(dateString);
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.
Upvotes: 243
Reputation: 455
I have a oneliner for this
dateInstance.toLocaleDateString().replaceAll("/", "-").split("-").reverse().join("-");
Upvotes: 3
Reputation: 12594
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
Upvotes: 22
Reputation: 20106
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]
Upvotes: 1627
Reputation: 4908
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:
Upvotes: 29
Reputation: 4688
I use this way to get the date in format yyyy-mm-dd :)
var todayDate = new Date().toISOString().slice(0, 10);
console.log(todayDate);
Upvotes: 411
Reputation: 15908
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];
};
Upvotes: 1
Reputation: 119
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.
Date
with vanilla string concatenationAssuming 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);
}
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);
}
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);
}
Temporal
-proposal polyfillThis 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);
}
Upvotes: 10
Reputation: 11355
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/
Upvotes: 996
Reputation: 772
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)
});
}
format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11
Upvotes: 64
Reputation: 4414
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.
Upvotes: 10
Reputation: 638
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
Upvotes: 0
Reputation: 442
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
Upvotes: -6
Reputation: 92727
.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);
Upvotes: 24
Reputation: 13023
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
Upvotes: 9
Reputation: 2981
If you use momentjs
, now they include a constant for that format YYYY-MM-DD
:
date.format(moment.HTML5_FMT.DATE)
Upvotes: 3
Reputation: 5205
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));
Upvotes: 0
Reputation: 11
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('/');
}
Upvotes: 0
Reputation: 2227
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));
}
});
Upvotes: 56