0

I've added two Bootstrap Datetime pickers to a HTML5 form. So far I can capture the DateTime value of each picker using the change event of the control.

Now I have a case where the time span difference between both DateTime pickers needs to be stored as a var.

I did come across an example similar to this ask here. But my short implementation below alerts a value of "Nan" instead of the expected time span difference when the actual time picker value is changed.

enter image description here

Question:

How can you calculate the time span between two date picker values in Javascript or JQuery?

Code gist:

var start;
var actual;

$("#OutageStartDisplay").on("dp.change", function (e) {
    start = $('#OutageStart').val(moment(e.date).format());
});


//On change of the ActualDisplay datetime picker 
//update's the Actual hidden field with the datetime.
$("#ActualDisplay").on("dp.change", function (e) {
    actual = $('#Actual').val(moment(e.date).format());

    //If the actual is set, calculate the outage duration
    var timeDiff = Math.abs(start - actual);
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
    alert(diffDays);

});
Community
  • 1
  • 1
Brian Var
  • 6,029
  • 25
  • 114
  • 212
  • Have you tried logging the values of all your variables after they're set? Perhaps one of them is not of the type you're expecting. – Frank Tan Jul 12 '16 at 21:56

1 Answers1

1

Since you're using moment, you can use moment.diff to get the time difference.

Your code also seems a bit bugged, when you do $("whatever").val(something), you're setting "whatever"s value to something and it returns $("whatever"), not the value. So you're trying to subtract a JQuery object from another JQuery object. But even if it returned the val, your val is a string - which you also cannot substract.

So you probably want this instead:

var start;
var actual;

$("#OutageStartDisplay").on("dp.change", function (e) {
    start = moment(e.date);
    $('#OutageStart').val(start.format());
});

$("#ActualDisplay").on("dp.change", function (e) {
    actual = moment(e.date);
    $('#Actual').val(actual.format());

    //If the actual is set, calculate the outage duration
    alert(actual.diff(start));
});
T. B.
  • 174
  • 7
  • Ok this seems to output the difference in milliseconds. Is there a cast to output this in hours? – Brian Var Jul 12 '16 at 22:36
  • 1
    http://momentjs.com/docs/#/displaying/difference/ You can pass a unit of measurement to moment.diff. `actual.diff(start, "hours")` – T. B. Jul 12 '16 at 22:38
  • Ok cool, is there any way I could convert the difference into a Day: HH: MM string or timepspan via JS? example 1 Day, 4 Hrs, 45 MIns – Brian Var Jul 12 '16 at 22:48
  • moment is new to me, it might have a way, but until there's something better, you could just do actual.diff(start, "days") + ": " + actual.diff(start, "hours") etc. – T. B. Jul 12 '16 at 23:16