javascript - 日期差异并使用 JS 插入同一数组

标签 javascript arrays loops

我有一个数组 propertyDetails,在这个数组中我有两个字段,分别是 activationDatedeActivationDate。我想从 propertyDetails 中获取 activationDate & deActivationDate 并计算日期差异并将其插入 propertyDetails 数组。如何实现?

my JS code

var doc = 
        {
            "name" : "property",
            "propertyDetails" : [
                {
                    "activationDate" : "2018-05-06 20:01:43",
                    "deActivationDate" : "2018-05-07 14:18:52"
                },
                {
                    "activationDate" : "2017-12-15 20:22:18",
                    "deActivationDate" : null
                }
            ]
        }
console.log(doc.propertyDetails[0].pedagogyID);

//date difference calculation code
var date1 = new Date('2013/11/04 00:00:00');
var date2 = new Date('2013/11/05 10:10:10'); //less than 1
var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from..
var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from..
var daysDiff = end - start; // exact dates

注意:deActivationDate null 表示取当前日期和时间并计算

最佳答案

您应该遍历属性详细信息数组并将差异附加到相应的对象中。

var doc = 
{
    "name" : "property name",
    "propertyDetails" : [
        {   
            "activationDate" : "2018-05-06 20:01:43",
            "deActivationDate" : "2018-05-05 14:18:52"
        },
        {
            "activationDate" : "2017-12-15 20:22:18",
            "deActivationDate" : null
        },
        {
            "activationDate" : "2017-12-15 20:21:11",
            "deActivationDate" : null
        }
    ]
}

// Loop though all the topics
for (var i = 0; i < doc.propertyDetails.length; i++) {

    // If they have a deactivation date, calculate the diff and put into an attribute named "dateDifference"
    if (doc.propertyDetails[i].deActivationDate == null) {
        doc.propertyDetails[i].deActivationDate = new Date()
    }

    doc.propertyDetails[i].dateDifference = getDaysDiff(new Date(doc.propertyDetails[i].activationDate), new Date(doc.propertyDetails[i].deActivationDate))
}

// Function to simplify and avoid code repetition.
function getDaysDiff(begin, end) {
    var beginDays = Math.floor(begin.getTime() / (3600 * 24 * 1000))
    var endDays = Math.floor(end.getTime() / (3600 * 24 * 1000))
    return endDays - beginDays
}

关于javascript - 日期差异并使用 JS 插入同一数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53783130/

相关文章:

android - 在 Android 中使用 JSON 从网站解析数组

javascript - 具有特定值的 Mongoose 模式属性

javascript - Drupal - 将自定义 JS 和 CSS 添加到面板

c - 为什么具有负索引的数组有效?

C++控制台游戏,故障重新切换语句以在二维数组中移动字符

arrays - 绑定(bind)变量的潜在变化导致 DO 循环的性能下降

c - 我正在尝试创建一个函数来接受用户输入的回文。为什么我输入一个数组后,它会自动输入其余的数组?

python - 迭代字典列表中的值 PYTHON

javascript - 在 MapMyindia map 上显示多个标记

javascript - JS : replace text char by char, 可以包含h​​tml标签