function dateFormat(dateVal, fmt = "YYYY-mm-dd HH:MM:SS") {
dateVal = dateVal || Date.now();
const date = new Date(dateVal);
let ret;
const opt = {
"Y+": date.getFullYear().toString(),
"m+": (date.getMonth() + 1).toString(),
"d+": date.getDate().toString(),
"H+": date.getHours().toString(),
"M+": date.getMinutes().toString(),
"S+": date.getSeconds().toString()
};
for (let k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt);
if (ret) {
fmt = fmt.replace(
ret[1],
ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
);
}
}
return fmt;
}
console.log("=== dateFormat():", dateFormat());
const day0 = new Date(new Date().toLocaleDateString()).getTime();
const m0 = new Date().setDate(1);
const m9 = new Date(m0);
m9.setMonth(new Date().getMonth() + 1);
m9.setDate(0);
const mS0 = new Date(m0);
mS0.setMonth(new Date().getMonth() - 1);
mS0.setDate(1);
const mS1 = new Date(mS0);
mS1.setMonth(new Date().getMonth());
mS1.setDate(0);
console.info(
"最近一小时===",
dateFormat(new Date() - 1000 * 60 * 60),
dateFormat()
);
console.info(
"今日===",
dateFormat(new Date(new Date().toLocaleDateString()).getTime()),
dateFormat(
new Date(new Date().toLocaleDateString()).getTime() +
1000 * 60 * 60 * 24 -
1000
)
);
console.info(
"昨日===",
dateFormat(day0 - 1000 * 60 * 60 * 24),
dateFormat(day0 - 1000)
);
console.info("本月===", dateFormat(m0), dateFormat(m9));
console.info("上个月===", dateFormat(mS0), dateFormat(mS1));
console.info(
"最近一周===",
dateFormat(new Date() - 1000 * 60 * 60 * 24 * 7),
dateFormat()
);
console.info(
"最近一月===",
dateFormat(new Date() - 1000 * 60 * 60 * 24 * 31),
dateFormat()
);