如何把长度13位的时间戳转换为以下格式:
type | 格式 | 说明 |
---|---|---|
1 | xxxx年xx月xx日 | 显示为 2022年06月29日 |
2 | xxxx-xx-xx | 显示为 2022-06-29 |
3 | xx-xx | 显示为 06-29 (月-日) |
4 | xx | 只显示月 06 |
5 | xx | 只显示日 29 |
6 | xxxx.xx.xx xx:xx:xx | 显示为 2022.06.29 12:00:45 |
7 | xxxx-xx-xx xx:xx:xx | 显示为 2022-06-29 12:00:45 |
8 | xxxx-xx-xx xx:xx | 显示为 2022-06-29 12:00 |
9 | xx-xx xx:xx | 显示为 06-29 12:00 |
补充说明:time为要转换的日期时间戳,type为日期格式
如需要的时间格式为 5-4 14:45 那么直接调用该方法 timeStamp2String(createtime,9)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>时间戳转换为日期格式</title>
</head>
<body>
</body>
<script type="text/javascript">
function timeStamp2String(time, type) { // time=>时间戳、 type=>转换类型
var datetime = new Date();
datetime.setTime(time);
var year = datetime.getFullYear();
var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
var hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
var minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
var second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
if (type == '1') {
return year + "年" + month + "月" + date + "日";
}
if (type == '2') {
return year + "-" + month + "-" + date;
}
if (type == '3') {
return month + "-" + date;
}
if (type == '4') {
return month;
}
if (type == '5') {
return date;
}
if (type == '6') {
return year + "." + month + "." + date + " " + hour + ":" + minute + ":" + second;
}
if (type == '7') {
return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}
if (type == '8') {
return year + "-" + month + "-" + date + " " + hour + ":" + minute;
}
if (type == '9') {
return month + "-" + date + " " + hour + ":" + minute;
}
}
var date = timeStamp2String(1652508000000, 8)
// 打印结果 2022-05-14 14:00
</script>
</html>