我有以下数组,有一些字段,例如 dateofbirth
,其中我需要删除时间并将格式更改为 MM-DD-YYYY
。
var records = [
{
"recordno":"000001",
"firstname":"Bo",
"middlename":"G",
"lastname":"Dallas",
"gender":"male",
"dateofbirth":"2014-05-31T18:30:00.000Z",
"dateofdeath":null,
"_id":"538c701c84ee56601f000063",
},
{
"recordno":"000001",
"firstname":"Bo",
"middlename":"G",
"lastname":"Dallas",
"gender":"male",
"dateofbirth":"2014-05-31T18:30:00.000Z",
"dateofdeath":null,
"_id":"538c701c84ee56601f000067",
},
];
如何为所有以 Date
类型作为数据类型的字段转换数组中的日期格式?
最佳答案
数组中的日期是日期对象吗?您想将它们转换为字符串吗?那么也许这会起作用。
for (var i = 0; i < records.length; ++i) {
var birthDate = new Date(records[i].dateofbirth);
var newBirthDateString = ('0' + birthDate.getDate()).slice(-2) + '-'
+ ('0' + (birthDate.getMonth()+1)).slice(-2) + '-'
+ birthDate.getFullYear();
records[i].dateofbirth = newBirthDateString;
if (records[i].dateofdeath !== null) {
var deathDate = new Date(records[i].dateofdeath);
var newDeathDateString = ('0' + deathDate.getDate()).slice(-2) + '-'
+ ('0' + (deathDate.getMonth()+1)).slice(-2) + '-'
+ deathDate.getFullYear();
records[i].dateofdeath = newDeathDateString;
}
}
关于javascript - 数组 - 转换所有日期字段的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24161175/