問題描述
我創建了一個應用程序,它接受 HTML 輸入并通過 JavaScript 在本機日歷事件上創建一個事件.它從 <input type="datetime-local">
中花費時間,并且由于選擇了不同的時區,因此它輸入了不同的時間.如果我輸入 1 o'clock PM 作為時間,它將返回 8 o'clock AM.
I've created an app that takes in HTML inputs and goes through JavaScript to create an event on a native calendar events. It takes the time from the <input type="datetime-local">
, and it's putting in a different time because it's picking a different time zone. If I enter 1 o'clock PM as a time it will return 8 o'clock AM.
<input type="datetime-local" id="startDate" name="startDate">
還有 JavaScript:
And the JavaScript:
var startDate = new Date($("#startDate").val());
任何幫助都會很棒.如果需要,我可以發布更多代碼.
Any help would be awesome. I can post more code if needed.
推薦答案
HTML5 datetime-local
輸入類型將返回一個 string 值,其中包含日期和 ISO8601 格式的時間,精確到分鐘,沒有任何時區偏移.
The HTML5 datetime-local
input type will give you a string value back, which contains the date and time in ISO8601 format, with minute precision, and without any time zone offset.
例如:2014-07-12T01:00
JavaScript
日期對象在從字符串中解析日期時是出了名的不一致.在大多數實現中,當您提供這樣的字符串時,它會錯誤地假定該值是 UTC.因此,您返回的 Date
對象將根據您本地計算機的時區偏移量進行調整.
The JavaScript
date object is notoriously inconsistent when it comes to parsing dates from strings. In most implementations, when you provide a string like this, it erroneously assumes the value is in UTC. Therefore, the Date
object you get back will be adjusted by the time zone offset from your local computer.
有兩種方法可以解決這個問題:
There are two approaches to work around the problem:
選項 1
將字符串處理為可能被 Date
對象的解析器解釋為本地時間的格式.具體來說,將破折號 (-
) 替換為正斜杠 (/
),并將 T
替換為空格.
Manipulate the string to a format that will likely be interpreted as local time by the Date
object's parser. Specifically, replace the dashes (-
) with forward slashes (/
) and replace the T
with a space.
var s = $("#startDate").val();
var startDate = new Date(s.replace(/-/g,'/').replace('T',' '));
選項 2
使用具有更強大的日期解析能力的庫.有幾種可用.其中最流行的是 moment.js.
Use a library with more capable date parsing abilities. There are several available. One of the most popular is moment.js.
Moment.js 有很多選項,但碰巧默認行為正是您所需要的.因此,您可以將字符串傳遞給 moment 構造函數而無需任何參數.
Moment.js has lots of options, but it just so happens that the default behavior is exactly what you need. So you can just pass the string to the moment constructor without any parameters.
var s = $("#startDate").val();
var startDate = moment(s).toDate();
這篇關于HTML 輸入類型 datetime-local 設置錯誤的時區的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!