Hour difference between two times(HH:MM:SS a)in momentjs
Asked Answered
B

14

49

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
Blanks answered 20/4, 2015 at 10:53 Comment(2)
possible duplicate of Get hours difference between two dates in Moment JsBizet
@ShaunakD duplicate is not accetable cause will return asTOTAL valuesCrossway
B
33

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";

}
Blanks answered 20/4, 2015 at 11:55 Comment(0)
P
80

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/

Paralyse answered 20/4, 2015 at 11:9 Comment(3)
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 wrongTarango
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.Paralyse
We can use the duration.hours() and duration.minutes() rather than applying logic on asMinutes()Hypnoanalysis
B
33

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";

}
Blanks answered 20/4, 2015 at 11:55 Comment(0)
L
15
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');
Lonne answered 20/4, 2015 at 11:1 Comment(4)
It's return hour only, not minutes :( .Blanks
@RameshRajendran You asked total hours in the question. So, what's your exact expectation ?Lonne
@RameshRajendran I don't think moment has inbuilt support for thisLonne
@RameshRajendran Check this one - #1788439Lonne
H
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());
Hydrastis answered 20/6, 2019 at 10:19 Comment(0)
W
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>
Wonacott answered 28/6, 2019 at 11:24 Comment(0)
C
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); 
}
Consideration answered 10/2, 2020 at 19:25 Comment(0)
C
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");
Cribwork answered 27/11, 2015 at 1:46 Comment(0)
A
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
Abreact answered 5/3, 2017 at 5:36 Comment(0)
S
1

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');
Souterrain answered 9/5, 2018 at 13:49 Comment(3)
That's really ugly code... is there anything your code does better than the other?Parka
The question was how can you do this in momentjs, this is how and its in one line.Souterrain
This is the only answer that allows easily changing the format (e.g. HH:mm:ss to mm:ss)Aynat
C
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)

Cryptoclastic answered 22/3, 2023 at 19:48 Comment(0)
B
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

Blanks answered 20/4, 2015 at 11:21 Comment(0)
S
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");
Synchronize answered 13/9, 2017 at 8:15 Comment(0)
P
-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('');
}
Prefer answered 16/7, 2021 at 12:48 Comment(2)
Any explanation would help viewer a lot.Greenwood
Your code snippet doesn't work. Maybe just use code fences rather than pretend it's a runnable snippet?Fathometer
L
-2
var startTime = moment("12:16:59");
var endTime = moment("06:12:07");

var duration = moment.duration(endTime.diff(startTime));
var hours = duration.asHours();
Layoff answered 20/4, 2015 at 11:2 Comment(1)
Moment constructor like this is discouraged and will be removed in future. Try to use with format :)Lonne

© 2022 - 2024 — McMap. All rights reserved.