2

I am using the following code at this codepen to try to populate a datetime-local input element with today's data and time. What they have on this tutorial does not work. I also tried what is in this SO post but also does not seem to work. How do can I set the datetime to today's date and time into a datetime-local input element. Thank you.

HTML:

<input type="datetime-local" id="datetime" name="datetime"> 

JS:

let today = new Date().toISOString(); document.getElementById('datetime').value = today; console.log(today); 
1

3 Answers 3

6

You may try this:

let today = new Date(); today.setMinutes(today.getMinutes() - today.getTimezoneOffset()); document.getElementById('datetime').value = today.toISOString().slice(0, -1); console.log(today);
<input type="datetime-local" id="datetime" name="datetime">

Sign up to request clarification or add additional context in comments.

Comments

1

Try this. It's the example used on MDN:

const today = new Date().toISOString(); const dateControl = document.querySelector('input[type="datetime-local"]'); dateControl.value = today; 

Comments

-1

Try this code.

 Number.prototype.AddZero= function(b,c){ var l= (String(b|| 10).length - String(this).length)+1; return l> 0? new Array(l).join(c|| '0')+this : this; }//to add zero to less than 10, var d = new Date(), localDateTime= [(d.getMonth()+1).AddZero(), d.getDate().AddZero(), d.getFullYear()].join('/') +', ' + [d.getHours().AddZero(), d.getMinutes().AddZero()].join(':'); var elem=document.getElementById("LocalDate"); elem.value = localDateTime;
<input type="datetime-local" name="name" id="LocalDate">

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.