1

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);
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
martinbshp
  • 1,073
  • 4
  • 22
  • 36
  • Does this answer your question? [HTML5 Input datetime-local default value of today and current time](https://stackoverflow.com/questions/24468518/html5-input-datetime-local-default-value-of-today-and-current-time) – Jonnel VeXuZ Dorotan Oct 20 '20 at 07:15

3 Answers3

4

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">
0

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;
Christian
  • 7,433
  • 4
  • 36
  • 61
-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">
Nbody
  • 1,168
  • 7
  • 33