48

I have two time without date

var startTime="12:16:59 am";
var endTime="06:12:07 pm";

I want to show the total hours in between the above times by using moment.js.

If it's not possible in moment.js then please let me know using by javascript.

Inputs:

var startTime="01:30:00 am";
var endTime="2:45:07 pm";

Expected Output:

1 hour and 15 minutes
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
  • possible duplicate of [Get hours difference between two dates in Moment Js](http://stackoverflow.com/questions/25150570/get-hours-difference-between-two-dates-in-moment-js) – Shaunak D Apr 20 '15 at 10:58
  • 1
    @ShaunakD duplicate is not accetable cause will return asTOTAL values – Paolo Falomo Jun 16 '17 at 09:31

14 Answers14

78

Try code below

// start time and end time
var startTime = moment('12:16:59 am', 'HH:mm:ss a');
var endTime = moment('06:12:07 pm', 'HH:mm:ss a');

// calculate total duration
var duration = moment.duration(endTime.diff(startTime));

// duration in hours
var hours = parseInt(duration.asHours());

// duration in minutes
var minutes = parseInt(duration.asMinutes()) % 60;

alert(hours + ' hour and ' + minutes + ' minutes.');

Check fiddle here - https://jsfiddle.net/nil4you/gs69Lv5x/

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
nirmal
  • 2,143
  • 1
  • 19
  • 29
  • var startTime=moment("09:00:00 pm", "HH:mm:ss a"); var endTime=moment("04:00:00 am", "HH:mm:ss a"); var duration = moment.duration(endTime.diff(startTime)); var hours = parseInt(duration.asHours()); var minutes = parseInt(duration.asMinutes())%60; alert (hours + ' hour and '+ minutes+' minutes.'); Ouput is -17 hours. But it should have been 7 hours. Can you please tell me if i am doing something wrong – Sandeep Nov 21 '18 at 16:04
  • 1
    yes I saw that, it's happening when we put pm before am. Mostly people do calculate only when it's day changed. I have found solution but it's not a robust. Once I have robust solution probably by today, then I will update my answer. – nirmal Nov 22 '18 at 02:42
32

Get Hours

I got the hours by using this code

endTime.diff(startTime, 'hours')

Get Minutes

i got the minutes by using this below code

var mins = moment.utc(moment(endTime, "HH:mm:ss").diff(moment(startTime, "HH:mm:ss"))).format("mm")

My Working code is

$scope.UpdateTimeSheet = function (rowEntity) {   
  if (rowEntity.StartTime.toString().length != 11) {
    rowEntity.StartTime = moment(rowEntity.StartTime).format("hh:mm:ss a");
  }

  if (rowEntity.EndTime.toString().length != 11) {
    rowEntity.EndTime = moment(rowEntity.EndTime).format("hh:mm:ss a");
  }

  var startTime = moment(rowEntity.StartTime, "hh:mm:ss a");
  var endTime = moment(rowEntity.EndTime, "hh:mm:ss a");

  var mins = moment.utc(moment(endTime, "HH:mm:ss").diff(moment(startTime, "HH:mm:ss"))).format("mm")

  rowEntity.TotalHours = endTime.diff(startTime, 'hours') + " Hrs and " + mins + " Mns";

}
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
14
var startTime = moment("12:16:59 am", 'hh:mm:ss a');
var endTime = moment("06:12:07 pm", 'hh:mm:ss a');

endTime.diff(startTime, 'hours');
Vigneswaran Marimuthu
  • 2,452
  • 13
  • 16
10
//Get start time and end time
var startTime = moment("12:16:59 am", "HH:mm:ss a"),
endTime = moment("06:12:07 pm", "HH:mm:ss a");
  1. Method 1

var dif = moment.duration(endTime.diff(startTime));
console.log([dif.hours(), dif.minutes(), dif.seconds()].join(':'));
console.log('dif in Mins: ', (dif.hours() * 60) + dif.minutes());
  1. Method 2

console.log('hrs: ', moment(endTime).diff(startTime, 'hours'));
console.log('dif in Mins: ', moment(endTime).diff(moment(startTime), 'minutes'));
  1. Method 3

var hrs = moment.utc(endTime.diff(startTime)).format("HH");
var min = moment.utc(endTime.diff(startTime)).format("mm");
var sec = moment.utc(endTime.diff(startTime)).format("ss");
console.log([hrs, min, sec].join(':'));
  1. Formatted output

var dif = moment.duration(endTime.diff(startTime));
console.log(dif.humanize());
Manish Thomas
  • 171
  • 1
  • 6
4

myStart = "01:30:00 am";
myEnd = "2:45:07 am";

function getTimeDiff(start, end) {

  return moment.duration(moment(end, "HH:mm:ss a").diff(moment(start, "HH:mm:ss a")));
}

diff = getTimeDiff(myStart, myEnd)
console.log(`${diff.hours()} Hour ${diff.minutes()} minutes`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
4

This worked for me; the best solution so far

function calculateTimeDifference() {
    var date1 = new Date();
    var date2 = new Date();

    var diff = date2.getTime() - date1.getTime();

    var msec = diff;
    var hh = `0${Math.floor(msec / 1000 / 60 / 60)}`;
    msec -= hh * 1000 * 60 * 60;

    var mm = `0${Math.floor(msec / 1000 / 60)}`;
    msec -= mm * 1000 * 60;

    var ss = `0${Math.floor(msec / 1000)}`;
    msec -= ss * 1000;

    return hh.slice(-2) + ":" + mm.slice(-2) + ":" + ss.slice(-2); 
}
blurfus
  • 13,485
  • 8
  • 55
  • 61
Sam
  • 41
  • 1
3
var startTime = moment("12:16:59 am", 'hh:mm:ss a');
var endTime = moment("06:12:07 pm", 'hh:mm:ss a');

var totalHours = (endTime.diff(startTime, 'hours'));
var totalMinutes = endTime.diff(startTime, 'minutes');
var clearMinutes = totalMinutes % 60;
console.log(totalHours + " hours and " + clearMinutes + " minutes");
Tarik Fojnica
  • 665
  • 6
  • 15
3
var start = moment.duration("09:45", "HH:mm");
var end = moment.duration("10:30", "HH:mm");
var diff = end.subtract(start);
diff.hours(); // return hours
diff.minutes(); // return minutes
Irfan Ashraf
  • 2,430
  • 21
  • 20
1
 const end = moment(event.end, "HH:mm:ss")
 const start = moment(event.start, "HH:mm:ss")
 const dif = moment.duration(end.diff(start));
 const formattedDiff = dif.minutes() > 0 ? `${(dif.hours() + dif.minutes() / 60)} hrs` : `${dif.hours()} hrs`
// Result: 1.5 hrs / 2 hrs / 4.25 hrs

I came up with this solution to show up difference in hour(s) (minutes converted, you can use Math.floor for minutes maybe but my case the minutes are always half/quarter)

spideyinf
  • 31
  • 6
0

I got it from @Vigneswaran Marimuthu

var startTime = moment("12:16:59 am", 'hh:mm:ss a');
var endTime = moment("06:12:07 pm", 'hh:mm:ss a');

var result = endTime.diff(startTime, 'hours') + " Hrs and " +     
            endTime.diff(startTime, 'minutes') + " Mns";

If we want to get seconds, then you just rewrite the code "seconds" instead of hours

Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
0

For - "12:00:01" Format without am, pm format following os the code..

   var startTime = moment('12:00:01', 'hh:mm:ss a');
   var endTime = moment('13:00:10' , 'hh:mm:ss a');
   var totalHours = (endTime.diff(startTime, 'hours'));
   var totalMinutes = endTime.diff(startTime, 'minutes');
   var clearMinutes = totalMinutes % 60;
   alert(totalHours + " hours and " + clearMinutes + " minutes");
0

I know this is marked as already answered but you can literally just do...

moment.utc(moment.duration(moment(dateA).diff(moment(dateB))).asMilliseconds()).format('HH:mm:ss');
Tyler V
  • 272
  • 3
  • 11
-1

var fromtime = moment($('#fromtime').val(), "HH:mm");
var totime = moment($('#totime').val(), "HH:mm");
var dif = moment.duration(totime.diff(fromtime));
var diff = [dif.hours(), dif.minutes()].join(':');
if(diff != "NaN:NaN" && dif.hours()>=0 && dif.minutes()>=0){
    $('#duration').text([dif.hours(), dif.minutes()].join(':'));
}else{
    $('#duration').text('');
}
-2
var startTime = moment("12:16:59");
var endTime = moment("06:12:07");

var duration = moment.duration(endTime.diff(startTime));
var hours = duration.asHours();
Joe Austin
  • 557
  • 7
  • 24