javascript 计算AngularJS中两个日期之间的小时差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23059680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculating hours difference between two dates in AngularJS
提问by mmmm
I've got template which looks like this:
我有一个看起来像这样的模板:
<tr ng-repeat="task in tasks" class="thumbnail">
<td ng-model="task.id">{[{ task.id }]}</td>
<td ng-model="task.time_start">{[{ task.time_start | date : 'MMM d, y HH:mm' }]}</td>
<td ng-model="task.time_stop">{[{ task.time_stop | date : 'MMM d, y HH:mm' }]}</td>
<td>[here i want the time difference]</td>
<td><button ng-click="edit(task)">Update</button></td>
</tr>
and I want to count hours difference between task.time_stop
and task.time_start
. Is there anyway to do this "live"
, in template?
我想计算task.time_stop
和之间的小时差task.time_start
。无论如何要"live"
在模板中做到这一点?
回答by harishr
Use the Moment library for this:
为此使用 Moment 库:
moment.utc(moment(task.time_stop.diff(moment(task.time_start))).format("mm")
You can wrap this call in a function:
您可以将此调用包装在一个函数中:
$scope.timediff = function(start, end){
return moment.utc(moment(end).diff(moment(start))).format("mm")
}
or even better create a factory for this... to make it reusable
甚至更好地为此创建一个工厂......使其可重复使用
PS: update your code to call the $scope.timediff
to display the time difference:
PS:更新您的代码以调用$scope.timediff
以显示时差:
<td>timediff(task.start,task.end )</td>