1.年月日时分秒转时间戳
function getTimeFormat(zcTime){
let time = (new Date(zcTime).getTime()) / 1000; //除1000 是变成秒级的时间戳 不除就是毫秒级
return time;
}
getTimeFormat('2022-11-8 10:16:36');//此处可以是/或者-
//打印结果为:1667873796000
2.时间戳转年月日时分秒
function getTime(zcTime){
//时间戳为10位需*1000,时间戳为13位的话不需乘1000
var date = new Date(zcTime * 1000);
var Y = date.getFullYear() + '-';
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth()+1) : date.getMonth() + 1) + '-';
var D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
var h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
var m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes())+ ':';
var s = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
return Y + M + D + h + m + s;
}
getTime(1667873796);
//打印结果为:2022-11-8 10:16:36
3.倒计时(结束时间减去当前时间)
function lastTime(time){
var currentTime = new Date()
var setTime = new Date(time) //返回的是用户输入时间总的毫秒数
var times = (setTime - currentTime)/1000 //结束时间减当前时间
var day = parseInt(times / 60 / 60 / 24); //天
var hours = parseInt(times /60 /60 % 24) //时
var m = parseInt(times/ 60 % 60) //分
var s = parseInt(times % 60) //秒
day =day < 10 ? "0" +day :day;
hours =hours < 10 ? "0" +hours :hours;
m =m < 10 ? "0" +m :m;
s =s < 10 ? "0" +s :s;
return day + "天" + hours + "时" + m + "分"+ s +"秒"
}
console.log(lastTime('2022-11-9 10:36:33'));
如果需要倒计时秒效果的话再加个定时器,并判断如果结束时间减去当前时间小于等于0的话clearInterVal();