// 示例代码:使用 JavaScript 格式化日期
// 创建一个新的 Date 对象
let date = new Date();
// 定义一个格式化日期的方法
Date.prototype.format = function(format) {
let 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;
};
// 使用自定义的 format 方法格式化日期
console.log(date.format("yyyy-MM-dd hh:mm:ss")); // 输出格式化的日期字符串
new Date() 创建了一个表示当前日期和时间的 Date 对象。Date.prototype 添加一个名为 format 的方法,使得所有 Date 对象都可以调用这个方法来格式化日期。yyyy 表示四位数的年份。MM 表示两位数的月份(例如:01 到 12)。dd 表示两位数的日期(例如:01 到 31)。hh 表示两位数的小时(24 小时制)。mm 表示两位数的分钟。ss 表示两位数的秒。yyyy, MM, dd 等),生成最终的格式化日期字符串。上一篇:js string trim
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站