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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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)..
What do you get in other browsers ?
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
You should rather create dates from string using moment and use the diff method to create a duration.
Couldn't get the code properly formatted in a comment so I've edited my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.