2014-10-30 24 views
4

在角度,我試圖計算使用jQuery datepicker兩個選定日期之間的天數。它只返回null與我正在使用的功能..使用角度和jQuery datepicker計算天差異

但是,我不太清楚,如果它是功能或在角度使用datepicker ..它看起來像問題是功能,但它的作品,當我用它與jQuery的..

我的功能:

$scope.dayDiff = function(firstDate,secondDate){ 

    $scope.dayDifference = parseInt(Math.round((secondDate - firstDate)/(1000 * 60 * 60 * 24)));; 
} 

休息:http://jsfiddle.net/1mzgLywe/5/

提前感謝!

+0

您正試圖減去字符串,這是行不通的。 'secondDate'和'firstDate'是不是Date類型的字符串。 – MiTa 2014-10-30 09:29:10

回答

7

這裏是工作提琴請,link to fiddle

創建功能得到dateString通入new Date()

$scope.formatString = function(format) { 
    var day = parseInt(format.substring(0,2)); 
    var month = parseInt(format.substring(3,5)); 
    var year = parseInt(format.substring(6,10)); 
    var date = new Date(year, month-1, day); 
    return date; 
} 

修改,如下dayDiff功能,

$scope.dayDiff = function(firstDate,secondDate){ 
    var date2 = new Date($scope.formatString(secondDate)); 
    var date1 = new Date($scope.formatString(firstDate)); 
    var timeDiff = Math.abs(date2.getTime() - date1.getTime()); 
    var diffDays = Math.ceil(timeDiff/(1000 * 3600 * 24)); 
    alert(diffDays); 
} 
+0

您可以嘗試[momentum.js](http://momentjs.com/)解析日期。 – MiTa 2014-10-30 10:43:15

6

angular-moment訣竅! ...和(非常)其他更多。

使用amDifference過濾器:

獲取毫秒兩個日期之間的差異。參數是 日期,單位和usePrecision。日期默認爲當前日期。例如:

<span>Difference: {{ dateFrom | amDifference : dateTo : 'days' }} days</span>