HTML input type date and time without timezone off

2019-04-28 14:11发布

问题:

I am using HTML5 input date and input time for ionic development. By default, it binds as ISO Date String and change to UTC date time. It seems wrong to me as when user choose the date 2016-06-06, it may have become 2016-06-07 or 2016-06-05 depending on timezone offset. Similar situation for input type = time.

What my intention is to make the Date in ISO String to remain of what user chosen instead of offset it with timezone difference.

Something like input datetime-local but seems that datetime-local is not supported by mobile device.

I am finding something like input type="date-local" or "time-local".

回答1:

First of all it is interesting that type="datetime" has been removed from the HTML5 standard and instead only "datetime-local" exists, yet it appears that not every mobile browser implements it. For type="date", it doesn't have a time component, so just use the UTC date directly. True, converting a UTC date d to local is kind of ridiculous:

  • new Date(d.toLocaleDateString())

or

  • d.setMinutes(d.getMinutes()+d.getTimezoneOffset())

or

  • new Date(+d+d.getTimezoneOffset()*60000)

but what can you do?



回答2:

Javascript dates are always UTC, but you can get the local values as well as shown here: http://www.w3schools.com/jsref/jsref_obj_date.asp

getUTCHours() Returns the hour, according to universal time (from 0-23) getHours() Returns the hour (from 0-23)

The first one will always be translated to UTC from what was inputed. The second one will use the timezone offset to calculate what should be returned.