数组 - 转换所有日期字段的日期格式

时间:2014-06-11 10:57:09

标签: javascript arrays angularjs

我有以下数组,有一些字段,如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类型作为数据类型的所有字段转换日期格式?

2 个答案:

答案 0 :(得分:1)

数组中的日期是对象吗?你想将它们转换成字符串吗?那么也许这会奏效。

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;
    }    
}

答案 1 :(得分:1)

请检查以下代码。希望这能帮到你!

var records = [
    {
        "recordno":"RF-000001",
        "firstname":"Bo",
        "middlename":"G",
        "lastname":"Dallas",
        "gender":"male",
        "dateofbirth":"2014-05-31T18:30:00.000Z",
        "dateofdeath":null,
        "_id":"538c701c84ee56601f000063",
    },
    {
        "recordno":"RF-000001",
        "firstname":"Bo",
        "middlename":"G",
        "lastname":"Dallas",
        "gender":"male",
        "dateofbirth":"2014-05-31T18:30:00.000Z",
        "dateofdeath":null,
        "_id":"538c701c84ee56601f000067",
    },
];

for(var i=0;i<records.length;i++){
    if(records[i].dateofbirth){
        var splitDateTime = records[i].dateofbirth.split("T");
        var splitDate = splitDateTime[0].split("-");
        records[i].dateofbirth = splitDate[1] +"-"+ splitDate[2] +"-"+ splitDate[0];
    }
} 

JSFiddle网址:http://jsfiddle.net/mail2asik/YdBCq/1/

<强>更新

它根据日期字段进行转换。希望这能帮到你!

for(var i=0;i<records.length;i++){
    for( var attrName in records[i]){
        if(records[i][attrName].indexOf("T") == 10){
             var splitDateTime = records[i][attrName].split("T");
             var splitDate = splitDateTime[0].split("-");
             records[i][attrName] = splitDate[1] +"-"+ splitDate[2] +"-"+ splitDate[0];
        }

    }
}   

JSFiddle网址:http://jsfiddle.net/mail2asik/YdBCq/3/