Learning Learning - 5 months ago 26
AngularJS Question

How to calculate time difference of 2 datetime object in angular js

I am very new in angular js and I want to calculate time difference between

two datetime object with format
:


Hour:Minutes:Seconds


But i want to get double digit output in time :


Expected Output: 00 : 00 : 04


Input:

StartDate=2016-06-29 15:52:32.360

EndDate=2016-06-29 15:53:36.970

Expected output: 00 : 01 : 04


This is my code:

public class User
{
public int Id { get; set; }
public Nullable<System.DateTime> StartDateTime { get; set; }
public Nullable<System.DateTime> EndDateTime { get; set; }
}

Json output:

[
{
"Id": 121,
"StartDateTime": "\/Date(1467195752360)\/", //2016-06-29 15:52:32.360
"EndDateTime": "\/Date(1467195756970)\/", //2016-06-29 15:53:36.970
},
{
"Id": 122,
"StartDateTime": "\/Date(1467195752360)\/",// 2016-06-29 15:52:32.360

"EndDateTime": "\/Date(1467195758360)\/", //2016-06-29 15:53:36.970
}
]


code:

<td ng-repeat="item in User">
//How to display time difference here
<p> Hour : Minutes : Seconds </p
</td>


Can anybody please help me???

Answer

You can achieve it using filter in ng-repeat:

var app = angular.module('app', []);

app.controller('mainCtrl', function ($scope) {
  $scope.timeSlots = [  
     {  
        "startDate":1467195752360,
        "endDate":1467195756970
     },
     {  
        "startDate":1467195752360,
        "endDate":1467195758360
     }
  ];
});

app.filter("getDiff", function() {
  return function(time) {
    var startDate = new Date(time.startDate);
    var endDate = new Date(time.endDate);
    var milisecondsDiff = endDate - startDate;
    
      return Math.floor(milisecondsDiff/(1000*60*60)).toLocaleString(undefined, {minimumIntegerDigits: 2}) + ":" + (Math.floor(milisecondsDiff/(1000*60))%60).toLocaleString(undefined, {minimumIntegerDigits: 2})  + ":" + (Math.floor(milisecondsDiff/1000)%60).toLocaleString(undefined, {minimumIntegerDigits: 2}) ;
  
  }
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
   <p ng-repeat = "time in timeSlots" ng-bind="time | getDiff">
</body>
</html>