Setting datetime-local value from Date

I would like to set the local datetime input value with the current date and time. Right now I have an ugly solution that involves cutting the first 17 characters. In addition, it sets the time in GMT instead of local time. My code is as follows:

<input type="datetime-local" name="name" id="1234"> <script type="text/javascript"> var d = new Date(); var elem = document.getElementById("1234"); elem.value = d.toISOString().slice(0,16); </script> 

I have two problems with this code:

  • Is there a way to convert from Date to legal value without manually slicing the string?
  • I want the string to appear in datetime-local as DD/MM/YYYY, hh:mm (e.g. 05/11/2015, 14:10 she 13:10 in GMT, but I'm in GMT + 1, so I want display 14:10 ). Currently displayed on 05/11/2015, 01:10 PM . I would like to remove PM and display in local time.

This may be an XY problem, so if I do it completely wrong, and there is a better way to display datetime collectors in html, I would be happy to hear.

+6
source share
3 answers

The toISOString function toISOString responsible for converting your local date ( new Date ) to GMT.

If you do not want to use GMT then slice, you need to use the pure Date constructor and all getX functions, where X (days, month, year ...)

In addition, you need to expand the Number object with a function that helps you return 01 instead of 1 , for example, to save the format dd/mm/yyyy, hh/mm .

Let me name 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> 

Watch it

+1
source

Replace this line

 elem.value = d.toISOString().slice(0,16); 

from

 elem.value = d.toLocaleString(); 

It will still print "am / pm" at the end, but it will take care of setting the time for local values.

+1
source

Personally, I used:

 <input type="datetime-local" name="name" id="1234" value="<?php echo date('Ym-d');echo 'T';echo date (H);echo ':';echo date(i);?>"> 
0
source

All Articles