How to get the formatted date from data result?
var obj = data.map(row => ({
id: row[0],
status: row[1],
datepublished: row[2]
}));
This is the result when i didnt format the datepublished
field
[
{
"id": 440937003,
"status": "Not Available",
"datepublished": "2022-03-27T16:00:00.000Z"
}
]
var obj = data.map(row => ({
id: row[0],
status: row[1],
datepublished: new Date(row[2].getTime() - (row[2].getTimezoneOffset() * 60000 )).toISOString().split("T")
}));
This is my current result data
[
{
"id": 440937003,
"status": "Not Available",
"datepublished": [
"2022-03-28",
"00:00:00.000Z"
]
},
]
what I want result is
[
{
"id": 440937003,
"status": "Not Available",
"datepublished": "2022-03-28"
},
]
CodePudding user response:
const data = [
{
id: 440937003,
status: 'Not Available',
datepublished: '2022-03-27T16:00:00.000Z',
},
];
const parsedData = data.map(({ id, status, datepublished }) => ({
id,
status,
datepublished: datepublished.slice(0, 10),
}));
console.log(parsedData)
CodePudding user response:
Your ISO 8601 string is in UTC as the Z
indicates so split()[0]
or substring(0, 10)
are the best option if you need UTC.
In case you need your string in another timezone parse it first and then use toLocaleDateString()
with locale of en-CA
(this will print year-month-day
) and whatever timezone you need as an option like this:
// For UTC
const iso8601str = "2022-03-27T16:00:00.000Z";
const split = iso8601str.split("T")[0];
const substring = iso8601str.substring(0, 10);
// For another timezone
// parse first, then format in desired timezone
// locale "en-CA" ensures format of year-month-day
const asiaDateStr = new Date(iso8601str).toLocaleDateString(
"en-CA",
{ timeZone: "Asia/Shanghai" } // options objects which also takes timeZone as an argument
);
console.log("In UTC wiht split():", split);
console.log("In UTC with substring():", substring);
console.log("In Asia/Shanghai:", asiaDateStr);
Have a look at the MDN docs to see what options exist for timeZone
.