Home > Mobile >  How to add a certain amount of minutes in a DateTime Input in Javascript
How to add a certain amount of minutes in a DateTime Input in Javascript

Time:08-09

I have two Input Fields like these,

            <div >
                <label for="">Challenge Start Date and Time</label>
                <input type="datetime-local"  name="date" id = "date" value=""/>
            </div>

            <div >
                <label for="">Challenge End Date and Time</label>
                <input type="datetime-local"  name="end_date" id = "end_date" value=""/>
            </div>

What I want to do actually is whatever time the user sets in the "Start" Input, that time 45 minutes should be set to the 2nd Input Field.

So, I tried the following, but unfortunately, due to the conversion of the Input Time into the String, I am unable to call getMinutes() 45

var now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
document.getElementById('date').value = now.toISOString().slice(0,16);
now.setMinutes(now.getMinutes()   45);
document.getElementById('end_date').value = now.toISOString().slice(0,16);

document.getElementById('date').addEventListener('change', (e) => {
    const value = e.target.value; 
    value.setMinutes(value.getMinutes()   45);
    document.getElementById('end_date').value = now.toISOString().slice(0,16);
});

I get this error whenever I change the value of the First Input Field,

Uncaught TypeError: value.getMinutes is not a function

Can anyone please provide an solution to this problem?

CodePudding user response:

The value of a datetime-local field does not return a Date object. It returns a string representation of the date (ISO-8601).

Here you can find more information about the value property of an <input type="datetime-local">

To convert this to a Date object you can just pass the value to the constructor like this:

var myDate = new Date(e.target.value);

CodePudding user response:

Try this

this will change get the input from field1 to field2

const value = new Date(e.target.value); 
value.setMinutes(value.getMinutes()   45);
value.setMinutes(value.getMinutes() - value.getTimezoneOffset());
document.getElementById('end_date').value = value.toISOString().slice(0,16);

You Missed the timezoneminutes minus from the calculated value

CodePudding user response:

Write your onchange function like this:

document.getElementById('date').addEventListener('change', (e) => {

var date = new Date(document.getElementById('date').value);
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
date.setMinutes(date.getMinutes()   45);
document.getElementById('end_date').value=date.toISOString().substring(0, 16);

})
  • Related