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?
CodePudding user response:
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()
CodePudding user response:
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()
CodePudding user response:
Below are two ways to get the yyyy-mm-dd
string format that you asked about from a native JavaScript Date
object:
- Offsetting the date information according to the system time UTC offset:
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);
- Get the individual date parts and format them with a leading
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);