一、自定义方法
1、utc时间
// 格式化时间
formatTime() {
// 获取当前时间
let date = new Date(); // 也可以转换指定时间 let date = new Date('2024-01-01 01:01:01')
// 年
let year = date.getFullYear();
// 月
let month =
date.getMonth() + 1 < 10
? "0" + (date.getMonth() + 1)
: date.getMonth() + 1;
// 天
let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
// 小时
let hours =
date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
// 分钟
let min =
date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
// 秒
let seconds =
date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
return `${year}-${month}-${day} ${hours}:${min}:${seconds}`;
},
2、unix时间戳
// 格式化时间
formatTime(timestamp) {
// timestamp是毫秒数
let date = new Date(timestamp * 1000);
// timestamp 是秒数
// let date = new Date(timestamp);
// 年
let year = date.getFullYear();
// 月
let month =
date.getMonth() + 1 < 10
? "0" + (date.getMonth() + 1)
: date.getMonth() + 1;
// 天
let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
// 小时
let hours =
date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
// 分钟
let min =
date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
// 秒
let seconds =
date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
return `${year}-${month}-${day} ${hours}:${min}:${seconds}`;
},
二、Date对象方法转换
1、toLocalString
// 获取本地时间
var localDate = new Date().toLocaleString();
// 格式输出:2020/8/26, 12:00:00
2、toString
let date = new Date().toString();
// 输出格式:Wed Aug 26 2020 12:00:00 GMT+0200 (Central European Summer Time)