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