前端处理时间戳
一、时间戳的格式化
后台返回的时间戳,一般为毫秒数,例:
let time = 1602598605267//时间戳
//常见的格式化方法
formatDate(value, fmt) {
let getDate = new Date(value);
let o = {
'M+': getDate.getMonth() + 1,
'd+': getDate.getDate(),
'h+': getDate.getHours(),
'm+': getDate.getMinutes(),
's+': getDate.getSeconds(),
'q+': Math.floor((getDate.getMonth() + 3) / 3),
'S': getDate.getMilliseconds()
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (let k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
}
}
return fmt;
}
console.log(formatDate(1602598605267, "yyyy-MM-dd hh:mm:ss"))//"2020-10-13 22:16:45"
二、不同时区下 对时间戳的处理
getTimezoneOffset() 方法可返回格林威治时间和本地时间之间的时差,以分钟为单位。
getGLWZTime(time){
//time为传入时间戳,毫秒为单位
let hours = new Date().getTimezoneOffset()/60
//计算格林威治时间和本地时间之间相差几个小时
let millisecond = hours*3600000
//毫秒为单位的时差
let standardTime = time + (8*3600000)
//标准时间戳 = 传入时间戳 + 北京与格林威治的时差(传入时间戳以北京为基础)
let currentZone = standardTime + millisecond
// 当前时区时间 = 标准时间戳 + 本地与格林威治时差
return currentZone
}
总结
思路:
1.根据当前时间戳,计算出与格林威治的时差,相加就等于标准时间;
2.掌握了标准时间,想要计算出当前时区的时间,只要将标准时间+时差即可