最基础格式化时间 time为时间戳
clearTime(time) {
let nowTime = new Date(time)
let year = nowTime.getFullYear()
let month = (nowTime.getMonth() + 1) < 10 ? "0" + (nowTime.getMonth() + 1) : (nowTime.getMonth() + 1)
let day = nowTime.getDate() < 10 ? "0" + nowTime.getDate() : nowTime.getDate()
let hour = nowTime.getHours() < 10 ? "0" + nowTime.getHours() : nowTime.getHours()
let minutes = nowTime.getMinutes() < 10 ? "0" + nowTime.getMinutes() : nowTime.getMinutes()
let seconds = nowTime.getSeconds() < 10 ? "0" + nowTime.getSeconds() : nowTime.getSeconds()
let and = "-"
let point = ":"
nowTime = year + and + month + and + day + " " + hour + point + minutes + point + seconds
return nowTime
}
如果 time为时间格式 直接
clearTime(nowTime) {
let year = nowTime.getFullYear()
let month = (nowTime.getMonth() + 1) < 10 ? "0" + (nowTime.getMonth() + 1) : (nowTime.getMonth() + 1)
let day = nowTime.getDate() < 10 ? "0" + nowTime.getDate() : nowTime.getDate()
let hour = nowTime.getHours() < 10 ? "0" + nowTime.getHours() : nowTime.getHours()
let minutes = nowTime.getMinutes() < 10 ? "0" + nowTime.getMinutes() : nowTime.getMinutes()
let seconds = nowTime.getSeconds() < 10 ? "0" + nowTime.getSeconds() : nowTime.getSeconds()
let and = "-"
let point = ":"
nowTime = year + and + month + and + day + " " + hour + point + minutes + point + seconds
return nowTime
}
下面是封装代码
// 第一个参数为格式化时间是否带时分秒,带为true,不带为false 默认false
// 第二个参数为格式化的时间 不填默认转化当前时间 new Date()获取到的值不是字符串不能直接传入参数中 否则无法识别
// 第三个参数为是否为时间戳 如果为时间戳则为true, 不是则可不填, 默认为false
function getNowTime(ishave, time, isTimeStamp){
let nowTime
if (time){
if (isTimeStamp){
nowTime = new Date(time)
}else{
nowTime = time
}
}else{
nowTime = new Date()
}
let year = nowTime.getFullYear()
let month = (nowTime.getMonth() + 1) < 10 ? "0" + (nowTime.getMonth() + 1) : (nowTime.getMonth() + 1)
let day = nowTime.getDate() < 10 ? "0" + nowTime.getDate(): nowTime.getDate()
let hour = nowTime.getHours() < 10 ? "0" + nowTime.getHours(): nowTime.getHours()
let minutes = nowTime.getMinutes() < 10 ? "0" + nowTime.getMinutes(): nowTime.getMinutes()
let seconds = nowTime.getSeconds() < 10 ? "0" + nowTime.getSeconds(): nowTime.getSeconds()
let and = "-"
let point = ":"
if (ishave){
nowTime = year + and + month + and + day + " " + hour + point + minutes + point + seconds
}else{
nowTime = year + and + month + and + day
}
return nowTime
}
var b = getNowTime(true, 1564624526889, true)
console.log(b);
var c = getNowTime()
console.log(c);
var d = getNowTime(true)
console.log(d);
// var a = getNowTime(true, 'Tue Jan 25 2022 15:50:20 GMT+0800 (中国标准时间)') 错误示范XXXX
// console.log(a);