I’m relatively new in coding and maybe it is a basics question, but still. I have this issue - I have 2 datetime inputs (start_date & end_date). I need to make a restriction as the second date (end_date) must be after first date (start_ date). There are 4 problems:
All I found with google relates datepicker, but I do not use one. So I need a solution for datetime input.
I need a dynamic solution, related to user input (start date), meaning the user enters start date and the restriction didn’t allow him to enter an end date before the start date. (Start date as a min Date).
All JavaScript I knew are about setting manualy a min value, but I need a dynamic, input related solution.
The end date MUST NOT be disabled.
In this respect I don’t know how to solve this so I couldn’t add any JavaScript or JQuery, only html. Your help is appreciated!
<input id="date1" type="datetime-local" name="start_date" onchange="getDDadmopMS()">Start Date <br />
<input id="date2" type="datetime-local" name="end_date" onchange="getDDadmopMS()">End Date<br />
Well I found an answer for me. Not the elegant one, but the working one. I used get.Time function to get ms value from both dates and then I substrates them. The result come into a new field. Then using a second function I did an “if statement” that if the difference is zero or negative (meaning the end date is before the start date) an alert is shown. Here is the code. If someone have a better answer I will appreciate it.
<input id="date1" type="datetime-local" name="start_date" onchange="getDDadmopMS()">Start Date <br />
<input id="date2" type="datetime-local" name="end_date" onchange="getDDadmopMS()">End Date<br />
<input id="diffms" type="text" readonly="true" placeholder="Date2 - Date1 in (ms)"/> Date2 - Date1 in (ms) <br />
// get Difference Date2 and Date1 in MS
function getDDadmopMS() {
let twoDate = new Date(document.querySelector('#date2').value);
console.log(document.querySelector('#date1').value);
let oneDate = new Date(document.querySelector('#date1').value);
document.querySelector('#diffms').value = twoDate.getTime() - oneDate.getTime();
}
//get Restriction
function getRestriction() {
var restrict = parseFloat($("#diffms").val());
if (restrict <=0){
alert('Date2 must be after Date1');
}
}
$(document).ready(function() {
$('#date1').blur(function(event) {
getRestriction();
});
$('#date2').blur(function(event) {
getRestriction();
});
});