小程序 IOS时间转换bug

2022-11-22  本文已影响0人  萘小蒽

在项目中需要将时间相互转换,代码如下

    resetDate() {
        let date = new Date(this.searchData.time.toString()bug ‘/’代替‘-’
        console.log(`${date.getFullYear()}年${this.fields === 'month' ? (date.getMonth()) + 1 + '月' : ''}`)
        return `${date.getFullYear()}年${this.fields === 'month' ? (date.getMonth()) + 1 + '月' : ''}`
    }

在开发工具是没问题的 但是实机测试时 出现了问题,所有的转换在ios变成了NaN

image.png
按照网上反馈,需要将时间格式中的 ' - ' 变成' / '
    resetDate() {
        let date = new Date(this.searchData.time.toString().replace(/-/g,'/')); //IOS Date对象转换bug ‘/’代替‘-’
        console.log(`${date.getFullYear()}年${this.fields === 'month' ? (date.getMonth()) + 1 + '月' : ''}`)
        return `${date.getFullYear()}年${this.fields === 'month' ? (date.getMonth()) + 1 + '月' : ''}`
    }

但是this.fields === 'month'时 时间的格式为 YYYY-MM 时还是会出现NaN问题
原因是ios实机中 new Date(YYYY/MM)也会在后续转换出现NaN
根据自己的需求做了变换,补了一个日期变成了 YYYY/MM/DD

resetDate() {
        let time = this.searchData.time.toString().replace(/-/g,'/');//IOS Date对象转换bug ‘/’代替‘-’
        let isMonth = this.fields === 'month';
        if(isMonth){
             time = time +'/01' //iosbug
        }
        let date = new Date(time); 
        return `${date.getFullYear()}年${isMonth ? (date.getMonth()) + 1 + '月' : ''}`
    }
上一篇 下一篇

猜你喜欢

热点阅读