/**
* 获取当前时间 需要什么传什么
* nowTime("星期W") //星期一
* nowTime("YYYY-MM-DD hh:mm:ss") //2022-10-01 10:00:23
* nowTime("MM/DD/YYYY hh:mm") //02-21-2022 11:12
* nowTime("YYYY年MM月DD日 hh:mm:ss 星期W") // 2023年03月21日 20:30:14 星期六
* nowTime("YYYY") //2021
* nowTime("yyyy") //2021
* nowTime("dd") 23
* nowTime("C") 当前月份总天数
* nowTime("N") 当前时间 Tue 3ar 23 2021 17:28:59 GMT+0800 (中国标准时间)
*/
function nowTime(param) {
const date = new Date()
const d = {
N: date,//当前时间
"Y+": date.getFullYear(),//年
"y+": date.getFullYear(),//年
"M+": date.getMonth()+1, //月
"D+": date.getDate(), //日
"d+": date.getDate(), //日
"H+": date.getHours(), //时
"h+": date.getHours(), //时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
W: date.getDay(), //周
C: date, //获取当前月份的总天数
}
for (const k in d) {
if (new RegExp('(' + k + ')').test(param)) {
param = param.replace(RegExp.$1, () => {
if (k === "W") {
// 星期几
const week = ["日", "一", "二", "三", "四", "五", "六"]
return week[d[k]]
} else if (k === "C") {
const curYear = d[k].getFullYear()
const curMonth = d[k].getMonth() + 1
const curDay = new Date(curYear, curMonth, 0)
return curDay.getDate()
} else if (k === "Y+" || k === "y+" || RegExp.$1.length == 1) {
// 年份 or 小于10不加0
return d[k]
} else {
return ("00" + d[k]).substr(("" + d[k]).length) // 小于10补位0
}
})
}
}
return param
}
let date= nowTime("YYYY/MM/DD HH:mm:ss 星期W");
console.log(date); // 2022/07/26 10:11:07 星期三
JavaScript 获取当前时间
于 2023-07-26 10:05:24 首次发布