js處理時間格式之蘋果手機多8個小時問題 (實用、贊)

原文出處: https://blog.csdn.net/namechenfl/article/details/90241952 (參考)

一、問題: 
當我將一個後端回傳的字符串 “2020-06-03T16:14:18”  轉成時間
var d = new Date("2020-06-03T16:14:18"); 
 var div = document.getElementById("my-time")
 div.innerText = d.toString();

1、安卓和谷歌瀏覽器上顯示正常
Wed Jun 03 2020 16:14:18 GMT+0800(中國標準時間)

2、蘋果手機 (多了8小時
Thu Jun 04 2020 00:14:18 GMT+0800(CST)

二、解決方法:
自己寫一個字符串轉日期函數代替new Date()方法

// 字符串轉換成時間  ios中要把毫秒去掉
function toTime(strTime) {
    if (!strTime) {
        return '';
    }

    var myDate = new Date(strTime + '+0800');
    if (myDate == 'Invalid Date') {
        strTime = strTime.replace(/T/g, ' '); //去掉T
        strTime = strTime.replace(/-/g, '/');
        strTime = strTime.replace(/\.\d+/, ' ');//去掉毫秒
        myDate = new Date(strTime + '+0800');       
    }    

    return myDate;
}

當我們用 toTime() 函數轉換時間
var d = toTime("2020-06-03T16:14:18"); 
 var div = document.getElementById("my-time")
 div.innerText = d.toString(); 

1、安卓和谷歌瀏覽器上顯示正常 (與上面樣
Wed Jun 03 2020 16:14:18 GMT+0800(中國標準時間)

2、蘋果手機 (正常顯示我們想要的時間
Wed Jun 03 2020 16:14:18 GMT+0800(CST)

三、兼容性問題
到這一刻用 toTime函數問題似乎得以解決,但如果轉換一個帶"Z"符號日期格式如:
   "2020-10-05T14:23:34Z" 或 "2020-10-08T10:12:25.888Z" 
問題又來了, android 會 “少8小時”, iOS 直接返回 “Invalid Date” 了
幸運的是,帶"Z"符號日期格式的字符串如果用new Date()轉,在android 和 iOS下都能正常轉換,所以要在函數做一上分支處理即可

// 字符串轉換成時間  ios中要把毫秒去掉
function toTime(strTime) {
    if (!strTime) {
        return '';
    }

    //如果有“Z”, 直接用new Date()轉換 
    if (date.indexOf("Z") > 0){
        return (new Date(strTime));
    }

    var myDate = new Date(strTime + '+0800');
    if (myDate == 'Invalid Date') {
        strTime = strTime.replace(/T/g, ' '); //去掉T
        strTime = strTime.replace(/-/g, '/');
        strTime = strTime.replace(/\.\d+/, ' ');//去掉毫秒
        myDate = new Date(strTime + '+0800');       
    }    

    return myDate;
}

 

四、總結
用自定義函數toTime 代替原生 new Date() 方法可以解決蘋果手機多加8小時問題

 

 
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章