new Date(), //Sat May 22 2021 10:38:06 GMT+0800 (中国标准时间)
//返回时间戳
+new Date(); //1621651748005
Date.now();//1621651748005
new Date().getTime()//1621651748005
new Date().toJSON(), //2021-05-22T02:38:06.765Z
new Date().toISOString(), //2021-05-22T02:38:06.765Z
new Date().toDateString(), //Sat May 22 2021
new Date().toLocaleString(), //2021/5/22上午10:38:06
new Date().toLocaleDateString(), //2021/5/22
new Date().toLocaleTimeString(), //"上午10:40:24"
//加参数的
new Date(1621541748005).toLocaleString()//2021/5/21上午4:15:48
getDate()获取当前日期对象是几日(1-31)
getDay()获取当前日期对象是周几(返回0-6.0表示周日.1表示周一)
getMonth()获取当前月份(0-11.0表示一月.11表示12月)
geFullYear()获取当前年份
geHours()获取小时(0-23)
geMinutes()获取分钟(0-59)
geSeconds()获取秒数(0-59)
geMilliseconds()获取毫秒数
格式化日期
function dateFormat(date, fmt = "yyyy年MM月dd日") {
if (date == null) return null;
if (typeof date === "string") {
date = date.slice(0, 19).replace("T", " ").replace(/-/g, "/");
date = new Date(date);
} else if (typeof date === "number") {
date = new Date(date);
}
var o = {
"M+": date.getMonth() + 1,
"[Dd]+": date.getDate(),
"h+": date.getHours(),
"m+": date.getMinutes(),
"s+": date.getSeconds(),
"q+": Math.floor((date.getMonth() + 3) / 3),
S: date.getMilliseconds(),
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(
RegExp.$1,
(date.getFullYear() + "").substr(4 - RegExp.$1.length)
);
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1
? o[k]
: ("00" + o[k]).substr(("" + o[k]).length)
);
}
return fmt;
}
console.log(dateFormat("2022-11-02T02:51:56.373Z", "yyyy年MM月DD日 hh:mm:ss")); //2022年11月02日 02:51:56
console.log(dateFormat(new Date())); //2022年11月02日
console.log(dateFormat(1667358481422)); //2022年11月02日
常用格式为:yyyy-MM-dd HH:mm:ss
转载于 JS时间对象new Date()的常用方法和格式化时间日期