[英]Convert utc date time to local date time using JavaScript or jQuery
[英]parsing a UTC ISO date to a local time date in javascript/jquery
我已經嘗試搜索答案,盡管我找到的答案非常相似,但我認為它們並不是我要找的。 如果其他地方已經回答了,請原諒我。
我試圖解析JavaScript中的ISO日期,以便可以將其與客戶端系統日期進行比較,並根據ISO日期是在客戶端系統日期之前還是之后顯示信息。
在我需要支持IE8之前,這很好,現在我被困住了。
我創建了一個函數,因為我需要執行三個不同的日期。
例如,我的ISO日期為UTC時間的2015-12-22T11:59。
但是,一旦我的日期被解析,完整的日期將是本地時間的11:59,無論我測試哪個時區,在那個時區始終是11.59。
我知道我當前創建的函數對時區沒有任何作用,這就是我遇到的問題。 我不知道要添加什么來更改結束日期,以反映客戶端計算機的時區。
任何幫助或建議,將不勝感激。 我無法使用類似moments.js之類的內容,因為我有上傳限制。
jQuery是可用的。 或純JavaScript。
<script>
function setSaleContent() {
//creating a new date object that takes the clients current system time. so we can compare it to the dates stored in our array
var currentDate = new Date();
console.log(currentDate + " this is the clients date ");
//These variables actually come from an external array object, but I'm putting them in here like this for this example.
var destinations = {
freedate: "2015-12-16T11:59",
courierdate: "2015-12-22T11:59",
nextdaydate: "2015-12-23T11:59",
}
//fetch all the ISO dates from the array.
var freeDateISO = destinations["freedate"];
var courierDateISO = destinations["courierdate"];
var nextdayDateISO = destinations["nextdaydate"];
//I am creating this reusable function to split up my ISO date for the sake of IE8.. and create it into a date format that can be compared against another date. I know that this isn't doing anything with my timezone and that is where my problem lies.
function parseDate(str) {
var parts = /^(\d{4}).(\d{2}).(\d{2}).(\d{2}):(\d{2})/.exec(str);
if (parts) {
return new Date(parts[1], parts[2] - 1, parts[3], parts[4], parts[5]);
}
return new Date();
}
//I would like this date to change to reflect the time zone of the clients system time.
//currently returns the date at 11.59 regardless of timezone.
//If i was in GMT i would want it to say 11.59
//If i was in CT time I would like this to say 05.59
//If i was in Perth I would like this to say 19:59
var freeDate = parseDate(freeDateISO);
console.log(freeDate + " this is the converted date for IE")
}
window.onload = setSaleContent;
一種簡單的解決方案是將Z
附加到ISO日期以表示它采用UTC時間,例如2015-12-22T11:59Z
。
當JavaScript將日期解析為字符串時,它將自動將UTC日期轉換為本地時區。
雖然這很簡單,但可以使用new Date(str);
形式的解析調用new Date(str);
,它對以IE8和其他舊版瀏覽器為參數的數字參數進行的解析調用將無法正常工作。
存在用於解析帶時區的ISO日期的polyfill: IE7 / IE8中的Javascript JSON日期解析返回NaN
經過一些修改以接受輸入字符串,這可以替換您的自定義parseDate
函數。
或者,在新創建的日期上使用.getTimezoneOffset()
方法,實現自己的自定義日期操縱.getTimezoneOffset()
以解決本地時區問題,該方法會以分鍾為單位給出時區偏移量,但是您將不得不想出一種利用偏移量的方法由於JavaScript日期對象的方法有限,例如調整小時和分鍾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.