1

This is my code

var departureDateFormat = new Date("10/09/15T09:25:00");
var arrivalDateFormat = new Date("13/09/15T13:25:00");

$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[2];
      var duration = moment.duration(arrivalDateFormat - departureDateFormat);  //for reference of moment.js
      var minutes = (duration / (1000 * 60)) % 60;  // calliculating number of minutes
      var hours = ((moment.duration(arrivalDateFormat - departureDateFormat)).humanize());  // calliculating number of hours
      var timeInHours = ((hours == "an hour") ? 1 : hours.toString().substring(0, 1));
      item.stopsDurationTime = timeInHours + "hrs " + minutes + "ms";
      return timeInHours + "hrs " + minutes + "ms";

In the above code worked on IE , but it was not working on other browsers.Now i want to get difference between the above two dates by using angularJs/javascript.

mitra p
  • 440
  • 5
  • 15
  • Possible duplicate question http://stackoverflow.com/questions/15298663/how-to-subtract-two-angularjs-date-variables – Arun AK Sep 12 '15 at 09:05

1 Answers1

1

You should use:

var minutes = duration.minutes();
var hours = duration.hours();
return hours + "hrs " + minutes + "ms";

Humanizing and then extracting the individual values is just unneeded overhead. And moment can extract the hours and minutes for you so no need to compute from milliseconds.

Update:

Something like this:

var departureDate = moment("10/09/15T09:25:00", "DD/MM/YYYYTHH:mm:ss");
var arrivalDate = moment("13/09/15T13:35:10", "DD/MM/YYYYTHH:mm:ss");
var duration = moment.duration(arrivalDate.diff(departureDate));
var hours = Math.floor(duration.asHours());
var minutes = Math.floor(duration.asMinutes()-(hours*60));
return hours + "hrs " + minutes + "ms";

You have to define the format explicitly otherwise depending on your regional setting it will understand "10/09" as October, 9th or September, 10th. Then you create a duration object. And you convert it to a number of hours (using "floor" to get a whole number). Then you convert it again to a number of minutes and subtract the hours you already got.

Henri Benoit
  • 705
  • 3
  • 10