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
  • 5,616
  • 1
  • 18
  • 49
martinbshp
  • 1,023
  • 4
  • 19
  • 34
  • 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
  • 6,936
  • 4
  • 31
  • 53
-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">
n-ata
  • 913
  • 2
  • 24