js快速获取当前时间并且返回想要的格式

function backCurrentTime (type) {
    let currentTime=new Date( new Date() + 8 * 3600 * 1000 ).toJSON().substr(0,19).replace("T"," ");
    if(type=='y'){
        return currentTime.substr(0,4)
    }else if(type=='m'){
        return currentTime.substr(5,2)
    }else if(type=='d'){
        return currentTime.substr(8,2)
    }else if(type=='y-m'){
        return currentTime.substr(0,7)
    }else if(type=='y-m-d'){
        return currentTime.substr(0,10)
    }else if(type=='y-m-d-h-m'){
        return currentTime.substr(0,16)
    }else{
        return currentTime
    }
}
console.log('当前年',backCurrentTime('y') )
console.log('当前月',backCurrentTime('m') )
console.log('当前天',backCurrentTime('d') )
console.log('当前年-月-天',backCurrentTime('y-m-d') )
console.log('当前年-月-天-时-分',backCurrentTime('y-m-d-h-m') )
主要是利用toJSON转格林威治时间 在+8小时得到就是北京时间
参考地址:https://www.cnblogs.com/youwei716/p/14088544.html

posted @ 2021-05-15 12:39  南风晚来晚相识  阅读(365)  评论(0编辑  收藏  举报