前端通用的时间格式转化函数
一、当前时间转化为标准格式
function getFormatDate() {
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
month = (month<10)? '0'+ month : month;
day = (day<10)? '0'+ day : day;
hour = (hour<10)? '0'+ hour : hour;
minutes = (minutes<10)? '0'+ minutes : minutes;
seconds = (seconds<10)? '0'+ seconds : seconds;
let currentDate = year + "-" + month + "-" + day
+ " " + hour + ":" + minutes + ":" + seconds;
return currentDate;
}
console.log(getFormatDate())
运行结果如下:
注意:获取月份的时候要加1 (var month = date.getMonth() + 1)
二、时间戳转化为标准格式
情况一.首先需要怎样获取当前时间的时间戳
作为前端人员也应该知道怎样获取当前时间的时间戳
let time1 = new Date().valueOf();
let time2 = Date.now();
console.log(time1)
console.log(time2)
情况二.首先需要怎样获取当前时间的时间戳
在实际项目开发中,前端工作人员从后端拿到的时间往往是时间戳的形式,此时就需要我们前端人员来进行转化
function formatDate(datetime) {
let date = new Date(datetime); //datetime时间戳为13位毫秒级别,如为10位需乘1000
let month = ("0" + (date.getMonth() + 1)).slice(-2)
let sdate = ("0" + date.getDate()).slice(-2)
let hour = ("0" + date.getHours()).slice(-2)
let minute = ("0" + date.getMinutes()).slice(-2)
let second = ("0" + date.getSeconds()).slice(-2)
let thatDate = date.getFullYear() + "-" + month + "-" + sdate + " " + hour + ":" + minute + ":" + second;
// 返回
return thatDate;
}
console.log(formatDate(1667187334738)) // 2022-010-31 11:35:34
注意:需要转化的时间戳为13位,如果不够需在最后加0补齐