时间戳转日期格式
// 转换前格式:时间戳(秒) 、时间戳(毫秒)
// 转换后格式:年月日时分秒、年月日、时分秒、月日时
// 转换前 例:1555459200 、 1555459200000
// 转换后 例:2019-04-17 08:00:00 、 2019-04-17 08:00:00
// 格式:yyyy-mm-dd hh:mm:ss 、yyyy-mm-dd、hh:mm:ss、mm-dd hh:mm:ss、mm-dd
console.log(this.timeSwitch(1555459200000,'yyyy-mm-dd hh:mm:ss'))
console.log(this.timeSwitch(1555459200,'yyyy-mm-dd'))
console.log(this.timeSwitch(1555459200000,'hh:mm:ss'))
console.log(this.timeSwitch(1555459200,'mm-dd hh:mm:ss'))
console.log(this.timeSwitch(1555459200,'mm-dd'))
// 时间格式转换
timeSwitch(timestamp,formatText) {
// 区分是秒还是毫秒(长度判断)
if((timestamp+'').length == 10){
//秒
timestamp = timestamp*1000;
}else if((timestamp+'').length == 13){
//毫秒
timestamp = timestamp;
}else{
console.log('传入的时间戳格式错误')
return ;
}
// 时间格式转换
timestamp = new Date(timestamp);
var year = timestamp.getFullYear() + ''; //年
var month = timestamp.getMonth() + 1 + ''; //月
var date = timestamp.getDate() + ''; //日
var hour = timestamp.getHours() + ''; //时
var minute = timestamp.getMinutes() + ''; //分
var second = timestamp.getSeconds() + '';//秒
month = month.length == 1 ? '0' + month : month;
date = date.length == 1 ? '0' + date : date;
hour = hour.length == 1 ? '0' + hour : hour;
minute = minute.length == 1 ? '0' + minute : minute;
second = second.length == 1 ? '0' + second : second;
// 结果
let result = '';
// 判断formatText的格式
if(formatText == 'yyyy-mm-dd hh:mm:ss'){
result = year+'-'+month+'-'+date+' '+hour+':'+minute+':'+second;
}else if(formatText == 'yyyy-mm-dd'){
result = year+'-'+month+'-'+date;
}else if(formatText == 'mm-dd hh:mm:ss'){
result = month+'-'+date+' '+hour+':'+minute+':'+second;
}else if(formatText == 'mm-dd'){
result = month+'-'+date;
}else if(formatText == 'hh:mm:ss'){
result = hour+':'+minute+':'+second;
}else{
console.log('传入需要转换的格式错误')
return ;
}
//返回出去结果
return result;
},
时间戳转日期格式
最新推荐文章于 2023-12-11 17:06:29 发布