转换时间戳
const date = new Date("1997-7-12 08:22:12");
console.log(date);
console.log(date*1);
console.log(Number(date));
console.log(date.valueOf());
console.log(date.getTime());
时间戳转换为时间
const date = new Date();
const timestamp = date.valueOf();
console.log(timestamp);
console.log(new Date(timestamp));
获取时间函数
const date = new Date();
function dateFormat(date,format="YYYY-MM-DD HH:mm:ss"){
console.log(format);
const config ={
YYYY:date.getFullYear(),
MM:date.getMonth(),
DD:date.getDate(),
HH:date.getHours(),
mm:date.getMinutes(),
ss:date.getSeconds()
}
for(const key in config){
format = format.replace(key,config[key]);
console.log(key);
}
console.log(format);
return format;
}
console.log(dateFormat(date,"YYYY年MM月DD日"))
date首先获取当前时间,我们传入我需要的格式。
传入的format就变成我们传入的格式了。
再利用for in循环遍历config,config对象用于取出时间的年月日时分秒。
再利用replace函数,替换format里面的YYYY MM等。
年月日时分秒不能是同一字母构成。