gpt4 book ai didi

javascript - JavaScript 和 Moment.js 无法正确评估日期范围内的日期

转载 作者:太空宇宙 更新时间:2023-11-04 15:29:53 25 4
gpt4 key购买 nike

如果这看起来是一个愚蠢的问题,我提前道歉,但我以前从未使用过 Moment.js。

我有以下方法(从以前的开发人员继承的代码),并且无法理解为什么评估不起作用。我确信这是一件微不足道的事情。

注意:只有 if 语句中的日期 >= weekOne 才能计算出正确的日期。即使日期匹配,其他 else if 子句也不会计算。

var myObject = $scope.uptimeData;
var uptimeTotal = [];
if (myObject) {
var weekOne = moment().subtract(7, "days").format("YYYY-MM-DD");
var weekTwo = moment().subtract(14, "days").format("YYYY-MM-DD");
var weekThree = moment().subtract(21, "days").format("YYYY-MM-DD");
var weekFour = moment().subtract(28, "days").format("YYYY-MM-DD");
var weekFive = moment().subtract(35, "days").format("YYYY-MM-DD");
var weekSix = moment().subtract(42, "days").format("YYYY-MM-DD");
var weekSeven = moment().subtract(49, "days").format("YYYY-MM-DD");

var weekOneTotalSuccess = 0;
var weekTwoTotalSuccess = 0;
var weekThreeTotalSuccess = 0;
var weekFourTotalSuccess = 0;
var weekFiveTotalSuccess = 0;
var weekSixTotalSuccess = 0;
var weekOneTotalFail = 0;
var weekTwoTotalFail = 0;
var weekThreeTotalFail = 0;
var weekFourTotalFail = 0;
var weekFiveTotalFail = 0;
var weekSixTotalFail = 0;
Object.keys(myObject).map(function (key, index) {
if (myObject[key].successes) {
if (key >= weekOne) {
weekOneTotalSuccess = weekOneTotalSuccess + myObject[key].successes;
} else if (key >= weekTwo && key < weekThree) {
weekTwoTotalSuccess = weekTwoTotalSuccess + myObject[key].successes;
} else if (key >= weekThree && key < weekFour) {
weekThreeTotalSuccess = weekThreeTotalSuccess + myObject[key].successes;
} else if (key >= weekFour && key < weekFive) {
weekFourTotalSuccess = weekFourTotalSuccess + myObject[key].successes;
} else if (key >= weekFive && key < weekSix) {
weekFiveTotalSuccess = weekFiveTotalSuccess + myObject[key].successes;
} else if (key >= weekSix && key < weekSeven) {
weekSixTotalSuccess = weekSixTotalSuccess + myObject[key].successes;
}
else {

}
}
}
}

以下是数据示例:

"2017-05-03": {
"failures": 816,
"successes": 18378
},
"2017-05-04": {
"failures": 1067,
"successes": 22302
},
"2017-05-05": {
"failures": 1008,
"successes": 82599
},
"2017-05-07": {
"failures": 2724,
"successes": 142854
},
"2017-05-08": {
"failures": 1329,
"successes": 149028
}

最佳答案

问题

您正在比较两个字符串。例如,在第一次迭代中,您的值如下:

key => "2017-05-03"
weekOne => moment().subtract(7, "days").format("YYYY-MM-DD"); /* which returns a formatted string */

><运算符并不是真正注定要与字符串类型变量一起使用。

Note : Each of these operators will call the valueOf() function on each operand before a comparison is made.

回答

只要你使用Moment.js,就应该引用the MomentJS Query documentation section为了比较一个日期是否早于或晚于另一个日期。

关于javascript - JavaScript 和 Moment.js 无法正确评估日期范围内的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44889065/

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