我想用角度js计算两个日期之间的日期差异。我用了这段代码:
$scope.formatString = function(format) {
var year = parseInt(format.substring(0,5));
var month = parseInt(format.substring(6,8));
var day = parseInt(format.substring(9,10));
var date = new Date(year, month-1, day);
return date;
}
$scope.dayDiff = function(fromdate,todate){
var date2 = new Date($scope.formatString(fromdate));
var date1 = new Date($scope.formatString(todate));
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
return diffDays;
}
但它在同一个月内是正确的,但它不能在不同月份的两个日期之间做正确的计算。
答案 0 :(得分:1)
为什么不尝试使用String split
函数(docs)来解析你的日期,split会根据你的格式生成一个年,月,日的数组。重新输入。从那里你可以通过索引引用数组,比尝试正确排列子串偏移更容易:
$scope.formatString = function(format) {
var pieces = format.split('.'),
year = parseInt(pieces[0]),
month = parseInt(pieces[1]),
day = parseInt(pieces[2]),
date = new Date(year, month - 1, day);
return date;
}
看看这个工作示例:http://plnkr.co/edit/GgXjqA76IX5bzQEP56ux?p=preview
答案 1 :(得分:0)
最好使用现成的库。因为你不知道将来你还需要使用日期。我推荐sugarjs。
日期之间的差异可以通过以下方式找到。
error TS4053: Return type of public method from exported class has or is using name 'Observable' from external module "node_modules/rxjs/Observable" but cannot be named.