1.对Date的扩展,将 Date 转化为指定格式的String
1.(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
2.(new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
3.如下所示:
Date.prototype.Format = function (fmt) {
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
S: this.getMilliseconds(),
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.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;
};
4.使用例子
const t = new Date().Format("yyyy-MM-dd hh-mm-ss");
console.log("不加中文", t);
const t2 = new Date().Format("yyyy年MM月dd日 hh时mm分ss秒");
console.log("加中文", t2);
const t3 = new Date().Format("yyyy-MM-dd");
console.log("只显示年月日", t3);
const t4 = new Date().Format("hh-mm-ss");
console.log("只显示时分秒", t4);
4.方式2
export function formatDate(date, str) {
date = new Date(date);
str = str ? str : "yyyy/MM/dd hh:mm:ss";
if (/(y+)/.test(str)) {
str = str.replace(RegExp.$1, String(date.getFullYear()).substr(4 - RegExp.$1.length));
}
let o = {
"M+": date.getMonth() + 1,
"d+": date.getDate(),
"h+": date.getHours(),
"m+": date.getMinutes(),
"s+": date.getSeconds(),
};
for (let k in o) {
if (new RegExp(`(${k})`).test(str)) {
let stry = String(o[k]);
str = str.replace(RegExp.$1, RegExp.$1.length === 1 ? stry : ("00" + stry).substr(stry.length));
}
}
return str;
}
const t = formatDate(new Date(), "yyyy-MM-dd hh:mm:ss");
console.log("t", t);
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?