The problem:
I have two datetimepicker elements utilizing trent richardson's datetimepicker
The first element selects a start date/time and the second selects an end date/time. When a date/time is changed i want to check that the start event is still before the end event. If not: the datetimepicker should revert to it's previous value.
What i've tried
$("selector").datetimepicker(function(){
//other init values.
onSelect: function(){
var start = $("#startStamp").val();
var stop = $("#stopStamp").val();
if(calculateTimeDiff(start, stop) <= 0){
alert("Start time may not exceed end time");
$(this).datetimepicker("setDate",obj.lastVal);
}
}
}
calculateTimeDiff() is a function that returns number of milliseconds between start and end date.
What happens
If the date selected for start value is after the end value. Then everything acts like supposed. The value is reverted.
But if both start and end value is on the same date and the time is changed so that it exceeds the end value. Then the date value is set to current date and time value isn't reset at all. If the dialog is closed after that, no value is return to the input field.
I've tried console.log(obj) both when you change a date and when you just change the time. and found out that obj.lasVal isn't set when just the time is changed. (A bit odd, i think).
Question
What am i doing wrong or could this be done in some other way?
There is a better way! You can just constrain both fields so that the start date maximum is the end date and the end date minimum is the start date, using minDateTime
and maxDateTime
that take Date
objects like so:
$("#startStamp").datetimepicker({
dateFormat: "yy-mm-dd",
timeFormat: "HH:mm",
showSecond: false,
controlType: 'select',
maxDateTime: new Date($('#endStamp').val().replace(/-/g, "/")),
});
$("#endStamp").datetimepicker({
dateFormat: "yy-mm-dd",
timeFormat: "HH:mm",
showSecond: false,
controlType: 'select',
minDateTime: new Date($('#startStamp').val().replace(/-/g, "/")),
});
Update
Fix for safari added.