格式化当前时间
好像还没有 js 内置方法解决这个问题。
方法一:编写原生 js 函数
回忆 Node.js 学习时,进行 包开发 的内容部分
① 格式化函数编写
function dateFormat(dtStr) {
// 这个注意区别new Date()
const dt = new Date(dtStr);
const y = dt.getFullYear();
const m = fixZero(dt.getMonth() + 1);
const d = fixZero(dt.getDate());
const hh = fixZero(dt.getHours());
const mm = fixZero(dt.getMinutes());
const ss = fixZero(dt.getSeconds());
// 使用【模块🚩字符串】 来拼接
// return `YYYY-MM-DD hh:mm:ss`;
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
}
// 自定义补零函数
function fixZero(n) {
return n > 9 ? n : "0" + n;
}
② 使用函数对当前时间进行格式化
const t = new Date();
// 1、普通打印
console.log(t); // 2022-04-15T07:27:19.678Z
// 2、格式化打印
console.log(dateFormat(t)); // 2022-04-15 15:27:19
方法二:使用 day.js
<script src="./lib/dayjs.min.js"></script>
<script>
// 1、普通打印
console.log(new Date()); // 2022-04-15T07:27:19.678Z
// 2、格式化打印
console.log(dayjs().format("YYYY-MM-DD HH-mm-ss")); // 2022-04-15 15:27:19
</script>