Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js new date().format

作者:断念已残   发布日期:2026-06-25   浏览:117

// 示例代码:使用 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")); // 输出格式化的日期字符串

解释说明:

  1. 创建 Date 对象new Date() 创建了一个表示当前日期和时间的 Date 对象。
  2. 扩展 Date 原型:通过给 Date.prototype 添加一个名为 format 的方法,使得所有 Date 对象都可以调用这个方法来格式化日期。
  3. 格式化规则
    • yyyy 表示四位数的年份。
    • MM 表示两位数的月份(例如:01 到 12)。
    • dd 表示两位数的日期(例如:01 到 31)。
    • hh 表示两位数的小时(24 小时制)。
    • mm 表示两位数的分钟。
    • ss 表示两位数的秒。
  4. 正则表达式替换:使用正则表达式匹配并替换格式字符串中的占位符(如 yyyy, MM, dd 等),生成最终的格式化日期字符串。

上一篇:js string trim

下一篇:js date to string

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站