Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign javascript date to html5 datetime-local input

Tags:

DOM:

<input id="myTextbox" type="datetime-local" />

Javascript (jQuery):

$('#myTextbox').val(new Date().toISOString());

Doesn't work. The format of input[type=datetime-local] is supposed to be ISO 8601, which is what javascript's Date.toISOString() returns.

like image 828
Alexander Taylor Avatar asked Feb 27 '15 08:02

Alexander Taylor


People also ask

How do I change the input date format in HTML5?

To set and get the input type date in dd-mm-yyyy format we will use <input> type attribute. The <input> type attribute is used to define a date picker or control field. In this attribute, you can set the range from which day-month-year to which day-month-year date can be selected from.

Which HTML5 attributes can be used with HTML5 date input type to limit date selection?

The max attribute specifies the maximum value (date) for a date field. Tip: Use the max attribute together with the min attribute to create a range of legal values. Tip: To set or return the value of the min attribute, use the min property.


1 Answers

http://www.w3schools.com/jsref/jsref_toisostring.asp:

The toISOString() method converts a Date object into a string, using the ISO standard.

The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ

While ISO 8601 has some flexibility, the format of javascript's Date's toISOString() is exactly as shown above.

The 'Z' at the end means this is a UTC date. So, this representation includes timezone information. (Javascript dates are naturally in UTC time since they are internally represented as milliseconds since epoch.)

The format of HTML5 input with type=datetime-local must be ...

The following parts, in exactly the following order:

  • A date.
  • The literal string "T".
  • A time.

Example:

1985-04-12T23:20:50.52

1996-12-19T16:39:57

http://www.w3.org/TR/html-markup/input.datetime-local.html

This is still ISO 8601, but stricter, and it does not allow a timezone to be specified.

Luckily, removing the timezone is as easy as removing the trailing 'Z'.

var isoStr = new Date().toISOString();
$('#myTextbox').val(isoStr.substring(0,isoStr.length-1));
like image 155
Alexander Taylor Avatar answered Oct 07 '22 17:10

Alexander Taylor