Javascript – Calculating hours difference between two dates in AngularJS

angularjsdatejavascript

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?

Best Answer

Use the Moment library for this:

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:

<td>timediff(task.start,task.end )</td>