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

时间:2017-07-03 15:16:15

标签: javascript momentjs

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

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

注意:只有 at SexSelector.onInputChange (src/components/sex_selector.js:20:15) at Object.<anonymous> (src/test/sexSelector.test.js:31:22) at node_modules/p-map/index.js:42:16 at process._tickCallback (node.js:369:9) 语句中的日期>= weekOne才能评估正确的日期。即使日期匹配,其他if子句也不会评估。

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 {

            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

<强>问题

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

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

><运算符实际上并不适用于String Type变量。

  

注意:在进行比较之前,每个操作符都会调用每个操作数上的valueOf()函数。

<强>答案

只要您使用的是Moment.js,就应该参考the MomentJS Query documentation section来比较日期是在另一个日期之前还是之后。