jQuery本身不提供直接的日期格式化功能,但可以通过多种方式实现日期/时间的格式化。常见的方法包括使用原生JavaScript Date对象的方法、jQuery插件或自定义函数。
// 扩展Date对象的格式化方法
Date.prototype.format = function(format) {
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(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var 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;
};
// 使用示例
var now = new Date();
console.log(now.format("yyyy-MM-dd hh:mm:ss")); // 输出: 2023-05-15 14:30:45
推荐使用jQuery插件jquery-dateFormat
:
// 引入插件后使用
var formattedDate = $.format.date(new Date(), "yyyy-MM-dd");
console.log(formattedDate);
虽然moment.js不是jQuery插件,但它是处理日期时间的强大库:
// 引入moment.js后
var now = moment();
console.log(now.format('YYYY-MM-DD')); // 2023-05-15
console.log(now.format('MMMM Do YYYY, h:mm:ss a')); // May 15th 2023, 2:30:45 pm
function formatDate(date, format) {
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
format = format.replace("dd", day < 10 ? "0" + day : day);
format = format.replace("MM", month < 10 ? "0" + month : month);
format = format.replace("yyyy", year);
format = format.replace("hh", hours < 10 ? "0" + hours : hours);
format = format.replace("mm", minutes < 10 ? "0" + minutes : minutes);
format = format.replace("ss", seconds < 10 ? "0" + seconds : seconds);
return format;
}
// 使用示例
var today = new Date();
console.log(formatDate(today, "dd/MM/yyyy hh:mm:ss")); // 15/05/2023 14:30:45
| 格式字符 | 说明 | 示例 | |----------|---------------------|-----------| | yyyy | 4位年份 | 2023 | | yy | 2位年份 | 23 | | MM | 2位月份(01-12) | 05 | | M | 月份(1-12) | 5 | | dd | 2位日期(01-31) | 15 | | d | 日期(1-31) | 15 | | hh | 2位小时(00-23) | 14 | | h | 小时(0-23) | 14 | | mm | 2位分钟(00-59) | 30 | | m | 分钟(0-59) | 30 | | ss | 2位秒数(00-59) | 45 | | s | 秒数(0-59) | 45 |
getUTC*
系列方法以上方法可以根据项目需求选择使用,对于复杂的日期处理需求,推荐使用moment.js或类似的专门日期处理库。