javascriptjquerydatedatetimemindate

How to set a dynamic mindate in datetime input with JQuery?


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:

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 />

Solution

  • 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();
    });
    });