Get the current date and time year, month, day, hour, minute, second
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
}
print result:
Convert yyyyMMddHHmmss to Date type
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);
print result
yyyymmdd hh:mm:ss characters converted to 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);
print result
Mutual conversion between timestamp and date format in js:
1. Convert timestamp to date format:
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. Convert the date format to a timestamp:
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替代