I want to obtain a date in yyyy-mm-dd format from a JavaScript Date object.
new Date('Aug 5 2022').toISOString().split('T')[0]
From above line, I'm expecting 2022-08-05 but getting 2022-08-04
how to solve it?
This issue occurs because you try to convert to toISOString it automatically convert to UTC, I am confident you are not in UTC area. So to fix this use:
new Date('Aug 5 2022 GMT+00').toISOString().split('T')[0]
So, convert it to UTC then to toISOString()
GMT+00 you can also just write UTCnew Date().toLocaleDateString('en-CA') does the job without relying on parsing an unsupported format. There are a number of languages that will produce the same result (such as "sv").Your date gets converted to UTC. One way to fix this would be by adding UTC to your argument string.
new Date('Aug 5 2022 UTC').toISOString().split('T')[0]
Date.prototype.toISOString()
The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix Z. - Date.prototype.toISOString()
Below are two ways to get the yyyy-mm-dd string format that you asked about from a native JavaScript Date object:
const date = new Date();
const utcOffsetMs = date.getTimezoneOffset() * 60 * 1e3 * -1;
const offsetDate = new Date(date.getTime() + utcOffsetMs);
const dateStr = offsetDate.toISOString().slice(0, 10);
console.log(dateStr);
0 if necessary:function getDateString (date) {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const dayOfMonth = date.getDate();
return `${year}-${String(month).padStart(2, '0')}-${String(dayOfMonth).padStart(2, '0')}`;
}
const date = new Date();
const dateStr = getDateString(date);
console.log(dateStr);
date.toLocaleDateString('en-CA'). ;-)
"Aug 5 2022"is not in a format defined to be parseable by the spec. While it's possible that a certain implementation might recognize and handle this format, it is not guaranteed. See here for info about valid datestring formats including a link to the specification: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…