1.将一个时间转年月日时分秒
(1) 普通字符串时间可转为中国标准时间
let now = new Date("2020-12-12 13:00"); 得到:Sat Dec 12 2020 13:00:00 GMT+0800 (中国标准时间)
(2) 转为时间戳
let date=now.getTime(); 得到 1607749200000
(3) 转为 年月日时分秒
得到:2020年12月12日 13点00分00秒
let time = "2020-12-12 13:00";
let now = new Date(time); //Sat Dec 12 2020 13:00:00 GMT+0800 (中国标准时间)
let date=now.getTime(); // 时间戳 1607749200000
// 获取年
let yy = now.getFullYear();
// 获取月
let mm = now.getMonth() + 1;
// 获取日
let dd = now.getDate();
// h获取小时
let hh = now.getHours();
// 获取分钟
let min = now.getMinutes();
// 获取秒
let ss = now.getSeconds();
hh = hh < 10 ? "0" + hh : hh;
min = min < 10 ? "0" + min : min;
ss = ss < 10 ? "0" + ss : ss;
let date= `${yy}年${mm}月${dd}日 ${hh}点${min}分${ss}秒`
console.log(date) // 2020年12月12日 13点00分00秒
2.求已过去x天x时x分x秒
将现在时间的时间戳减之前时间的时间戳进行计算
let date = "2020-12-12 13:00"; //给的之前时间
let beforeTime = new Date(date).getTime(); //之前时间戳 1607749200000
let nowTime = new Date().getTime(); // 现在的时间戳 1648020150786
let time = nowTime - beforeTime; // 差别的时间戳 40271370582
let day=Math.floor(time/(1000*60*60*24))
let hours=Math.floor((time/(1000*60*60))%24)
let minutes=Math.floor((time/(1000*60))%60)
let seconds=Math.floor((time/1000)%60)
let formerlyTime=day+'天'+hours+'小时'+minutes+'分钟'+seconds+'秒'
//已过去466天2小时31分钟39秒
console.log('已过去'+ formerlyTime)