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
  • 6
  • 15
  • Possible duplicate question http://stackoverflow.com/questions/15298663/how-to-subtract-two-angularjs-date-variables – Thinker 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.

benohead
  • 655
  • 3
  • 9
  • Hi benohead, Your answer is correct but that code is working in only IE...but not other browsers.Actually I want duration in any format(seconds,minutes,hours).. – mitra p Sep 12 '15 at 09:39
  • What do you get in other browsers ? – benohead Sep 12 '15 at 09:40
  • 1
    new Date("10/09/15T09:25:00"); this is not converting date time format in other browsers .... It giving "Invalid Date" It is converting in IE only – mitra p Sep 12 '15 at 09:51
  • You should rather create dates from string using moment and use the diff method to create a duration. – benohead Sep 12 '15 at 09:53
  • Couldn't get the code properly formatted in a comment so I've edited my answer. – benohead Sep 12 '15 at 10:32