获取当前日期时间 年月日 时分秒
var date = new Date();
var year = date.getFullYear() // 年
var month = this.checkTime(date.getMonth() + 1) //月
var day = this.checkTime(date.getDate()) //日
var hour = this.checkTime(date.getHours()) //时
var minutes = this.checkTime(date.getMinutes()) //分
var seconds = this.checkTime(date.getSeconds()) //秒
console.log("获取当前日期时间",year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds);
function checkTime(i){
//月日时分秒不足10时,补全0
if(i < 10){
i = '0' + i
}
return i
}
打印结果:
yyyyMMddHHmmss转化成 Date类型
var dateStr = '20221112010359'
//匹配yyyyMMddHHmmss格式的日期
var pattern = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/;
//将时间格式化成 yyyy-MM-dd HH:mm:ss
var formatDateStr = dateStr.replace(pattern, '$1/$2/$3 $4:$5:$6');
//将时间转成Date
var formatDate = new Date(formatDateStr);
打印结果
yyyymmdd hh:mm:ss字符转换为Date
var dateString="20221112 01:03:59";
var pattern = /(\d{4})(\d{2})(\d{2})/;
var formatedDate = dateString.replace(pattern, '$1/$2/$3');
var date = new Date(formatedDate);
打印结果
js中时间戳与日期格式的相互转换:
1. 将时间戳转换成日期格式:
function timestampToTime(timestamp) {
var date = new Date(timestamp * 1000); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
var year = date.getFullYear() // 年
var month = this.checkTime(date.getMonth() + 1) //月
var day = this.checkTime(date.getDate()) //日
var hour = this.checkTime(date.getHours()) //时
var minutes = this.checkTime(date.getMinutes()) //分
var seconds = this.checkTime(date.getSeconds()) //秒
return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
}
function checkTime(i){
//月日时分秒不足10时,补全0
if(i < 10){
i = '0' + i
}
return i
}
console.log(timestampToTime(1669274673)); //2022-11-24 15:24:33
2. 将日期格式转换成时间戳:
var date = new Date('2022-11-24 15:24:33:123');
// 有三种方式获取
var time1 = date.getTime();
var time2 = date.valueOf();
var time3 = Date.parse(date);
console.log(time1); //1669274673123 精确到毫秒
console.log(time2); //1669274673123 精确到毫秒
console.log(time3); //1669274673000 只能精确到秒,毫秒用000替代