微信小程序時間轉換

mpvue微信小程序:時間轉換 Android和IOS兼容問題vue

Android和IOS在時間解析時分隔符不一樣
1.Android使用‘-’來分割
2.IOS使用‘/’來分割android

在ios中使用new Date('2019-06-17')返回的是null,ios在時間格式解析中不認識‘-’,須要替換爲‘/’;字符串的方法中有str.replace()方法。ios

字符串str.replace()方法
1.str.replace('須要替換的字符串', "新字符串") // 這種方式只能替換字符串中首個須要替換的字符;若是後邊還有想要替換的字符也不會進行替換
2.str.replace(/須要替換的字符串/g, "新字符串") // 使用正則表達式能夠替換字符串中全部須要替換的字符(若是是‘-’、‘/’等特殊字符記得加‘反斜槓’哦!)。正則表達式

formatDate(time) { // 接收參數格式 xxxx-xx-xx
        let newTime = '';
        let result = ''; // 接收時間
        wx.getSystemInfo({ // 微信小程序獲取設備系統信息
            success:function(res){ // 獲取系統信息成功
                if(res.platform == "devtools"){
                    console.log('我是PC');
                    newTime = time;
                }else if(res.platform == "ios"){
                    console.log('我是IOS');
                    newTime = time.replace(/-/g, '/'); // 系統爲IOS時用‘/’來分割
                }else if(res.platform == "android"){
                    console.log('我是android');
                    newTime = time;
                }
                let lr = new Date(newTime); // 傳入的過去時間
                let now = new Date(); // 當前時間
                let dt = now -lr;
                let second = dt / 1000; // 秒
                if(second < 3600) {
                    result = parseInt(s / 60) + '分鐘';
                } else if(second < 86400) {
                    result = parseInt(s / 60 / 60) + '小時';
                } else if(second <604800) {//在一週內
                    result = parseInt(s / 60 / 60 / 24) + '天';
                } else if(second <31104000) {
                    result = parseInt(s / 60 / 60 / 24 / 30) + '月';
                } else if(second <311040000) {
                    result = parseInt(s / 60 / 60 / 24 / 30 / 12) + '年';
                }
            }, fail(err){
                console.log('設備系統信息獲取失敗', err)
            },
        })
        return result
  }

這是我在使用mpvue開發微信小程序時遇到的一個時間轉換的問題,但願能對ni有所幫助;若是有什麼之後咱們能夠多多交流。小程序

相關文章
相關標籤/搜索