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.
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);
});
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));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.