gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:14:43 25 4
gpt4 key购买 nike

我有一个数组 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com