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

标签 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 类型作为数据类型的字段转换数组中的日期格式?

最佳答案

数组中的日期是日期对象吗?您想将它们转换为字符串吗?那么也许这会起作用。

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/

相关文章:

javascript - 在特定时间在 HTML5 Canvas 上绘制 SVG 文件

javascript - React 事件处理与 ref 和 media play

c - 尝试在 C 中分配结构数组的段错误

PHP数组到MYSQL数据库?

javascript - 需要处理 Angular UI 路由器中的动态参数,并相应地加载模板

javascript - this.props.getEvents 不是一个函数

javascript - 复制对象文字的更美观的方式?

javascript - Ng-repeat 不更新数组

AngularJS 用户界面路由器 : Not registering history state when navigating to tabs

javascript - 使用 jquery find 在 Angular Directive(指令)中获取 dom 元素