Setting value of datetime-local from Date
I ended up subtracting getTimezoneOffset
minutes to adjust the toISOString
value:
var now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
document.getElementById('dt').value = now.toISOString().slice(0,16);
<input id="dt" type="datetime-local" />
The toISOString
function is responsible of converting your local date (new Date
) into GMT.
If you don't want to use GMT then slice, you need to use the pure Date constructor and all of the getX functions, where X is (days, month, year...)
In addition, you'll need to extend the Number
object with a function that will help you to return 01
instead of 1
for example, to preserve the dd/mm/yyyy, hh/mm
format.
Let me call this prototype function AddZero
<input type="datetime-local" name="name" id="1234">
<script type="text/javascript">
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("1234");
elem.value = localDateTime;
</script>
See this
The following function will take a date object (e.g. new Date()
) and will return a string correctly formatted for <input type='datetime-local'>
.
const dateForDateTimeInputValue = date => new Date(date.getTime() + new Date().getTimezoneOffset() * -60 * 1000).toISOString().slice(0, 19)