js原声 时间戳格式化 年月日十分秒
2021-01-26 本文已影响0人
缓慢的蜗牛
// 时间格式化
function dateFormat(timeStamp, type) {
// 时间格式化
let time = new Date(timeStamp);
let YYYY = time.getFullYear();
let MM = (time.getMonth() + 1) < 10 ? ("0" + (time.getMonth() + 1)) : (time.getMonth() + 1);
let DD = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
let hh = time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
let mm = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
let ss = time.getSeconds() < 10 ? "0" + time.getSeconds() : time.getSeconds();
let dateType = type.trim() || type;
switch (dateType) {
case "YYYY":
return YYYY;
break;
case "YYYYMM":
return YYYY + "-" + MM;
break;
case "YYYYMMDD":
return YYYY + "-" + MM + "-" + DD;
break;
case "YYYYMMDD hh":
return YYYY + "-" + MM + "-" + DD + " " + hh;
break
case "YYYYMMDD hhmm":
return YYYY + "-" + MM + "-" + DD + " " + hh + ":" + mm;
break
case "YYYYMMDD hhmmss":
return YYYY + "-" + MM + "-" + DD + " " + hh + ":" + mm + ":" + ss;
break
case "hh":
return hh;
break
case "hhmm":
return hh + ":" + mm;
break
case "hhmmss":
return hh + ":" + mm + ":" + ss;
break
case "mmss":
return mm + ":" + ss;
break
case "ss":
return ss;
break
default:
return "时间类型错误,请检查!"
}
}