JavaScript日期比较无法正确评估

时间:2016-10-11 20:57:40

标签: javascript

此表达式的评估结果为true。为什么呢?

if ($scope.state.dateStart < $scope.state.previousStart || $scope.state.dateEnd > $scope.state.previousEnd) {

调试时,我可以看到值是相同的,因此表达式不应该为真:

enter image description here

编辑:在某些时候,之前的值设置如下:

$scope.state.previousStart = new Date($scope.state.dateStart);
$scope.state.previousEnd = new Date($scope.state.dateEnd);

编辑:这是角度工厂,显示最初如何定义值。

app.factory('historyRepository', ['$http', '$rootScope', function ($http, $rootScope) {
    var state = {
        allBatches: [],
        filteredBatches: [],
        selectedBatch: null,
        allStatuses: [],
        dateStart: new Date(),
        dateEnd: new Date(),
        previousStart: new Date(),
        previousEnd: new Date()
    }

    // Set initial start and end date times
    var date = new Date();
    date.setDate(date.getDate() - 7); // 7 days ago
    state.dateStart = new Date(date);
    state.previousStart = new Date(date);
    state.dateEnd.setHours(23, 59, 59, 999); // Use ending of end date. (hour,min,sec,millisec)
    state.previousEnd.setHours(23, 59, 59, 999); // Use ending of end date. (hour,min,sec,millisec)

    return state;
}]);

1 个答案:

答案 0 :(得分:1)

问题在于我的结束日期;具体而言,毫秒。使用现有日期设置日期时,不设置毫秒。需要设置毫秒才能使日期相等。

$scope.state.previousEnd = new Date($scope.state.dateEnd);
$scope.state.previousEnd.setMilliseconds(999);
// Now previousEnd and dateEnd are the same.

通过这样做,我能够看到日期不一样:

// Show milliseconds since January 1, 1970
console.log('dateEnd', $scope.state.dateEnd.getTime());
console.log('previousEnd', $scope.state.previousEnd.getTime());

这是输出:

    dateEnd 1476331199999
previousEnd 1476331199000