今天所讲一下时间戳如何转换成月日时分秒!
什么是时间戳
时间戳(timestamp)是一份能够表示一份数据在一个特定时间点已经存在的完整的可验证的数据。指格林威治时间自1970年1月1日(00:00:00 GTM)至当前时间的总秒数。
1).第一种转换,通过内置方法
let time_start = new Date('2021/06/18 08:00:00');
function timers(timer){
let year = timer.getFullYear(); //转换成年
let month = timer.getMonth() + 1; //转换成月 ,月注意要加1,因为外国月份是0 - 11月
let day = timer.getDate(); //转换成日
let hours = timer.getHours(); //转换成时
let minutes = timer.getMinutes(); //转换成分
let secend = timer.getSeconds(); //转换成秒
let str = `${supplement(year)}-${supplement(month)}-${supplement(day)} ${supplement(hours)}:${supplement(minutes)}:${supplement(secend)}`;
return str;
}
console.log(timers(time_start)); //2021-06-18 08:00:00
上面这种是通过特定的方法进行转换,很方便,但是还有一种复杂的方法,通过时间戳进行乘除换算得到年月日时分秒
2).第二种转换,通过换算得到
let time_start = new Date('2021/06/18 08:00:00');
let time_end = new Date('2021/07/17 11:00:00');
function timeDifference(timeStart, timeEnd) {
let timeStarts = timeStart.getTime(); //开始时间,转换成时间戳
let timeEnds = timeEnd.getTime(); //结束时间,转换成时间戳
let timer = timeEnds - timeStarts //将时间戳进行相减
let mouth = parseInt((timer / 1000 / 60 / 60 / 24 / 30)) //月
let day = parseInt((timer / 1000 / 60 / 60 / 24)) //日
let hours = parseInt((timer / 1000 / 60 / 60 % 24)); //时
let minutes = parseInt((timer / 1000 / 60 % 60)); //分
let seconds = parseInt((timer / 1000 % 60)); //秒
let str = supplement(day) + " " + supplement(hours) + ':' + supplement(minutes) + ":" + supplement(seconds)
if (mouth >= 1) {
return '天数大于一个月'
}else{
return str
}
}
console.log(timeDifference(time_start, time_end)); //29 03:00:00
第二种较第一种比较复杂,如果没有特定要求使用第二种,用第一种方法即可!
另外,我们在计算的时候,数字是单个出现的,但是我们想实现补0操作
function supplement(timer) {
if (timer < 10) {
return timer = '0' + timer;
} else {
return timer
}
}
以上就是对时间戳转换成时分秒一个简单的讲解!