JavaScript日期格式化:内置方法与自定义函数详解

作者:木棉

时间:2026-10-28

浏览:424

本文介绍JavaScript中Date对象的多种内置格式化方法,如toDateString、toISOString等,并详细讲解如何通过扩展Date.prototype实现自定义日期格式字符串,支持年、月、日、时、分、秒及毫秒的灵活组合输出。

文章目录

JavaScript内置日期格式化方法

在实际开发中,经常需要利用JavaScript内置的Date对象方法来处理日期格式,例如:

具体代码示例如下:

var d = new Date();
console.log(d); // 输出:Mon Nov 04 2013 21:50:33 GMT+0800 (中国标准时间)
console.log(d.toDateString()); // 获取日期字符串,输出:Mon Nov 04 2013
console.log(d.toGMTString()); // 获取格林威治时间字符串,输出:Mon, 04 Nov 2013 14:03:05 GMT
console.log(d.toISOString()); // 获取ISO 8601标准格式,输出:2013-11-04T14:03:05.420Z
console.log(d.toJSON()); // 输出:2013-11-04T14:03:05.420Z
console.log(d.toLocaleDateString()); // 转换为本地日期格式,具体表现取决于运行环境,输出:2013年11月4日
console.log(d.toLocaleString()); // 转换为本地日期和时间格式,具体表现取决于运行环境,输出:2013年11月4日 下午10:03:05
console.log(d.toLocaleTimeString()); // 转换为本地时间格式,具体表现取决于运行环境,输出:下午10:03:05
console.log(d.toString()); // 转换为完整字符串,输出:Mon Nov 04 2013 22:03:05 GMT+0800 (中国标准时间)
console.log(d.toTimeString()); // 转换为时间字符串,输出:22:03:05 GMT+0800 (中国标准时间)
console.log(d.toUTCString()); // 转换为世界协调时间字符串,输出:Mon, 04 Nov 2013 14:03:05 GMT

自定义日期格式化函数实现

若上述内置方法无法满足特定的格式需求,可以通过自定义函数来实现更灵活的日期格式化,示例如下:


具体代码示例如下:

Date.prototype.format = function(format) {
var date = {
"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+)/i.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
       }
for (var k in date) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1
? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
              }
       }
return format;
}
var d = new Date().format('yyyy-MM-dd');
console.log(d); // 2013-11-04

 

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章