JavaScript 扩展 Date 对象实现时间格式化
作者:开源拾贝时间:2026-10-27 22:18:03浏览:561
本文介绍如何在 JavaScript 中通过扩展 Date.prototype 实现自定义时间格式化功能。提供了完整的代码示例,展示如何将日期对象转换为指定格式的字符串,如年月日时分秒,并包含实际调用示例。
JavaScript Date 格式化实现
以下是相关代码实现。
/**
此部分用于定义时间对象的格式化方法。
*/
Date.prototype.format = function(format) {
/*
例如,格式参数可以设置为 "YYYY-MM-dd hh:mm:ss"。
*/
var o = {
"M+" :this.getMonth() + 1, // month
"d+" :this.getDate(), // day
"h+" :this.getHours(), // hour
"m+" :this.getMinutes(), // minute
"s+" :this.getSeconds(), // second
"q+" :Math.floor((this.getMonth() + 3) / 3), // quarter
"S" :this.getMilliseconds()
// millisecond
}
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().format("yyyy-MM-dd hh:mm:ss");
另一个示例代码如下。
new Date().format("yy-MM-dd hh:mm");作者最新文章
JS 怎么使用 pako.js 解压 gzip 数据流
2026-11-05 15:54:33
零基础先学JavaScript还是Python?对比学习难度与上手曲线
2026-11-05 14:47:40
JS代码反混淆:主流在线工具与本地软件推荐
2026-11-04 19:28:41
浏览器控制台查看格式化JSON有哪些实用技巧
2026-11-04 16:56:53
JS控制台打印基础:console.log语法与多参数用法
2026-11-04 09:23:11
