admin管理员组

文章数量:1410705

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);

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);
Share Improve this question edited Oct 20, 2020 at 7:28 MauriceNino 6,7671 gold badge32 silver badges74 bronze badges asked Oct 20, 2020 at 6:59 martinbshpmartinbshp 1,1734 gold badges25 silver badges37 bronze badges 1
  • Does this answer your question? HTML5 Input datetime-local default value of today and current time – Jonnel VeXuZ Dorotan Commented Oct 20, 2020 at 7:15
Add a ment  | 

3 Answers 3

Reset to default 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">

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;

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

本文标签: Trying to set datetimelocal using JavaScriptStack Overflow