我这里有一个JavaScript数组。我需要将生日值与设定日期进行比较,并使用新的键值更新记录。
var employees = [
{
"internalid":"1",
"name":"Abe Anderson",
"email":"aanderson@javascript.com",
"birthdate":"9/25/1974",
"supervisor":"3",
"2012 Revenue":"100000.00",
"2013 Revenue":"0.00"
}
];
我在这里写的很好,
for (var i = 0; i < employees.length; i++) {
var cDate = new Date("2014/01/01");
var newDate = cDate.getMonth()+1 + '/' + cDate.getDate() + '/' + cDate.getFullYear();
var eBday = employees[i].birthdate;
}
我很难写出数学来正确地比较这两个日期。谁能帮我?我需要计算每个人在他或她的生日之前剩下的天数并更新JavaScript数组。我被卡住了!
答案 0 :(得分:1)
我建议使用momentJS。它是去javascript日期处理的库。
在momentJS中,您可以使用moment.diff
方法:http://momentjs.com/docs/#/displaying/difference/
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
这家伙详细解答了如何使用momentJS进行比较:https://stackoverflow.com/a/22601120/6624456
答案 1 :(得分:0)
试试这个。
var employees = [{
"internalid": "1",
"name": "Abe Anderson",
"email": "aanderson@javascript.com",
"birthdate": "9/25/1974",
"supervisor": "3",
"2012 Revenue": "100000.00",
"2013 Revenue": "0.00"
}];
for (var i = 0; i < employees.length; i++) {
employees[i].daysToBirthday = DaysToBirthdayFromToday(employees[i].birthdate);
}
console.log(employees);
function DaysToBirthdayFromToday(birthdayString) {
"use strict";
var currentYear = new Date().getFullYear();
//get today midnight
var today = new Date(currentYear, new Date().getMonth(), new Date().getDate());
var birthdayParts = birthdayString.split("/");
var yearBirthday = new Date(currentYear, birthdayParts[0] - 1, birthdayParts[1]);
var timDiffInMilliSeconds = yearBirthday.getTime() - today.getTime();
var timDiffInDays = timDiffInMilliSeconds / (1000 * 60 * 60 * 24);
return timDiffInDays < 0 ? 0 : timDiffInDays; // set zero if past
}