随笔 - 42,  文章 - 0,  评论 - 3,  阅读 - 24148

1、方法

const formatDate = (date, format = "YYYY-MM-DD HH:mm:ss") => {
if (!date) {
return "";
}
const d = new Date(date);
// 年
if (/YYYY/.test(format)) {
format = format.replace(/YYYY/, d.getFullYear());
}
// 月份
const month = d.getMonth() + 1;
if (/MM/.test(format)) {
const monthStr = month < 10 ? "0" + month : month;
format = format.replace(/MM/, monthStr);
} else if (/M/.test(format)) {
format = format.replace(/M/, month);
}
// 日期
const dates = d.getDate();
if (/DD/.test(format)) {
const dateStr = dates < 10 ? "0" + dates : dates;
format = format.replace(/DD/, dateStr);
} else if (/D/.test(format)) {
format = format.replace(/D/, dates);
}
// 小时
const hours = d.getHours();
if (/HH/.test(format)) {
const hoursStr = hours < 10 ? "0" + hours : hours;
format = format.replace(/HH/, hoursStr);
} else if (/H/.test(format)) {
format = format.replace(/H/, hours);
} else if (/hh/.test(format)) {
const hoursMin = hours > 12 ? hours - 12 : hours;
const hoursStr = hoursMin < 10 ? "0" + hoursMin : hoursMin;
format = format.replace(/hh/, hoursStr);
} else if (/h/.test(format)) {
const hoursMin = hours > 12 ? hours - 12 : hours;
format = format.replace(/h/, hoursMin);
}
// 分
const minutes = d.getMinutes();
if (/mm/.test(format)) {
const minutesStr = minutes < 10 ? "0" + minutes : minutes;
format = format.replace(/mm/, minutesStr);
} else if (/m/.test(format)) {
format = format.replace(/m/, minutes);
}
// 秒
const seconds = d.getSeconds();
if (/ss/.test(format)) {
const secondsStr = seconds < 10 ? "0" + seconds : seconds;
format = format.replace(/ss/, secondsStr);
} else if (/s/.test(format)) {
format = format.replace(/s/, seconds);
}
return format;
};

2、用法

posted on   丶凉雨拾忆  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示