0

I've been working on calculating the total hours, minutes and seconds between two times using the moment.js library. The problem I have is that the calculations don't recognise that it's a day and return more hours than what is there. I'll give you an example:

I want to know how many hours are between 21:00 and 06:00, the answer is 9, however, the calculation brings back -15, this is also technically correct. I need to tell moment that it should use a day to calculate this value. I can get it to work if I use a DateTime picker but I don't want to use that as the user is only required to provide a time.

My application uses KendoUI for MVC and moment.js, moment.duration.format.js and moment.range.js

Here is my code which will return -15

@(Html.Kendo().TimePicker().Name("start").Value("21:00"))
@(Html.Kendo().TimePicker().Name("end").Value("06:00"))

<button class="btn btn-default btn-success" onclick="calc()">Plot</button>

Here is the javascript that works with this.

 function calc() {

   window['moment-range'].extendMoment(moment);

    console.clear();

    var dformat = "HH:mm:ss";                     
    var start = $("#start").data("kendoTimePicker").value();
    var end = $("#end").data("kendoTimePicker").value();           

    var startTime = moment(kendo.toString(start));
    var endTime = moment(kendo.toString(end));
    var duration = moment.duration(endTime.diff(startTime));
    var hours = parseInt(duration.asHours());
    console.log(hours);    
}

If we change this to use DateTimePicker instead, it understands there is a day and calculates 9 hours. So how do I get around this? How can I achive this without using a datetime picker? Can I leaverage moment.js startof day or something?

HerrGanzorig
  • 51
  • 1
  • 14
Yanayaya
  • 2,044
  • 5
  • 30
  • 67
  • 2
    See [here](https://stackoverflow.com/q/45414587/4131048), you are getting a moment object for the current day, use `isBefore` and `add`. – VincenzoC Nov 14 '17 at 16:38

1 Answers1

0

Thanks to @VincenzoC I have managed to fix this problem. Here is the code which checks if the end time is before the start time and if it is, add a single day. This means the resulting time is accurate.

var startTime = moment(start);
var endTime = moment(end);

if (endTime.isBefore(startTime))
{
    endTime.add(1, 'd');

}

//
//After the above condition has been passed, calculate the difference
var duration = moment.duration(endTime.diff(startTime));

//
//Any format you want
console.log(duration.format("HH"))
Yanayaya
  • 2,044
  • 5
  • 30
  • 67