1、时间戳转化为时间
const timestampToTime = (timestamp) => {
timestamp = timestamp ? timestamp : null;
let date = new Date(timestamp);//时间戳为10位也就是秒需*1000,时间戳为13位也就是毫秒的话不需乘1000
let Y = date.getFullYear() + '-';
let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
return Y + M + D + h + m + s;
}
const getDate = timestampToTime()
console.log(getDate)
时间戳(毫秒)转化为时间
2、时间转换为时间戳
const timeToTimestamp = (time) => {
let timestamp = Date.parse(new Date(time).toString());
console.log(time + "的时间戳为:" + timestamp);
return timestamp;
}
const getDate = timeToTimestamp()
console.log(getDate)
时间转化为时间戳(毫秒)
3、转化为年月日时分秒
const getTimeNow = () => {
let time = new Date();
let hour = time.getHours();
let minute = time.getMinutes();
let second = time.getSeconds();
let week = '';
let date = '';
const weekInfo = [
{
id: 0,
week: "星期日"
},
{
id: 1,
week: "星期一"
},
{
id: 2,
week: "星期二"
},
{
id: 3,
week: "星期三"
},
{
id: 4,
week: "星期四"
},
{
id: 5,
week: "星期五"
},
{
id: 6,
week: "星期六"
}
]
return (time.getFullYear())+"年"+(time.getMonth()+1)+"月"+time.getDate()+"日"+" "+hour+':'+minute+':'+second+' '+weekInfo.find(i => i.id === time.getDay()).week;
}
const getCurrentDate = getTimeNow()
console.log(getCurrentDate)
我们这里直接封装为一个简单的轮子,直接供于外部调用