Datetime-local limit past and future date JavaScript

Viewed 255

I have 2 inputs for datetime-local (start-time & end-time). I want to limit the start date to select only the last 72 hours which I did but i cannot restrict future time. I only want today and only last 3 days. And for end time only today and next 3 days. This is my code:

<input type="datetime-local" name="start_timestamp" id="start_timestamp" required>
            
<input type="datetime-local" name="end_timestamp" id="end_timestamp" required>

<script>
    //Do not let to select START TIME  in the PAST
    var today = new Date();
    var past = new Date(today.setDate(today.getDate() - 3)).toISOString().slice(0, 16);
    

    document.getElementsByName("start_timestamp")[0].min = past;
    document.getElementsByName("start_timestamp")[0].max = today;
</script>


            
1 Answers

See here a possible fix.

<input type="datetime-local" name="start_timestamp" id="start_timestamp" required>
            
<input type="datetime-local" name="end_timestamp" id="end_timestamp" required>




<script>
    //Do not let to select START TIME  in the PAST
    let today = new Date();
    let past = new Date(today.setDate(today.getDate() - 3)).toISOString().slice(0, 16);
    today = new Date().toISOString().slice(0, 16);

    document.getElementsByName("start_timestamp")[0].min = past;
    document.getElementsByName("start_timestamp")[0].max = today;
    
    document.getElementsByName("end_timestamp")[0].min = past;
    document.getElementsByName("end_timestamp")[0].max = today;
    
</script>

Related