jquery日期格式化函数
jQuery 日期格式化函数实现
jQuery 本身没有内置日期格式化函数,但可以通过扩展 jQuery 或直接使用 JavaScript 实现。以下是几种常见的实现方式:
使用原生 JavaScript 扩展
Date.prototype.format = function(format) {
const 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(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (let k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
};
// 使用示例
const date = new Date();
console.log(date.format("yyyy-MM-dd hh:mm:ss"));
作为 jQuery 插件实现
$.formatDate = function(date, format) {
if (!date) return '';
if (typeof date === 'string') {
date = new Date(date.replace(/-/g, '/'));
}
const map = {
"M": date.getMonth() + 1, // 月份
"d": date.getDate(), // 日
"h": date.getHours(), // 小时
"m": date.getMinutes(), // 分
"s": date.getSeconds(), // 秒
"q": Math.floor((date.getMonth() + 3) / 3), // 季度
"S": date.getMilliseconds() // 毫秒
};
format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
let v = map[t];
if (v !== undefined) {
if (all.length > 1) {
v = '0' + v;
v = v.substr(v.length - 2);
}
return v;
} else if (t === 'y') {
return (date.getFullYear() + '').substr(4 - all.length);
}
return all;
});
return format;
};
// 使用示例
const dateStr = $.formatDate(new Date(), 'yyyy-MM-dd');
使用第三方库
对于更复杂的日期处理需求,推荐使用专门的日期处理库:
-
Moment.js(已停止维护,但仍在广泛使用)
moment().format('YYYY-MM-DD HH:mm:ss'); -
Day.js(Moment.js 的轻量替代)
dayjs().format('YYYY-MM-DD HH:mm:ss'); -
date-fns

import { format } from 'date-fns'; format(new Date(), 'yyyy-MM-dd HH:mm:ss');
注意事项
- 原生 JavaScript 实现需要注意时区问题
- 日期字符串解析时,不同浏览器对格式的支持可能不一致
- 对于复杂的国际化需求,建议使用专业日期库
- 在 jQuery 项目中,可以将格式化函数添加到 jQuery 命名空间下方便全局调用
以上方法可以根据项目需求选择适合的实现方式,对于简单项目可以使用原生实现,复杂项目推荐使用专业日期库。






