原生js实现Date.format方法

解释:RegExp.$1为取得字符串中符合正则表达式的部分;

  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), //季度
            "f+": this.getMilliseconds() //毫秒
        };
        console.log(o)
        if (/(y+)/.test(format)) {
            console.log(RegExp.$1)
            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;
    }

    // export default Date.prototype.format


    // 然后我们使用其格式日期
   
    const now = new Date().format("yyyy-MM-dd HH:mm:ss");
    console.log(now)
  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaScript的Date对象是用来操作日期时间的对象,它包含了很多有用的方法和属性。其中,Date.prototype.format()方法是一个常用的方法,用于格式化日期为特定格式。 Date.prototype.format()的语法如下: ```javascript Date.prototype.format(format) ``` 其中,format是一个字符串,用于指定输出日期的格式。可以使用以下格式占位符: - "yyyy" 代表年份,例如:"2021" - "MM" 代表月份,例如:"01" 表示一月份 - "dd" 代表日期,例如:"01" 表示第一天 - "HH" 代表小时,24小时制,例如:"12" 表示12小时 - "mm" 代表分钟,例如:"30" 表示30分钟 - "ss" 代表秒钟,例如:"00" 表示0秒钟 以下是一个使用Date.prototype.format()方法的示例: ```javascript let date = new Date(); let formattedDate = date.format("yyyy-MM-dd HH:mm:ss"); console.log(formattedDate); ``` 输出结果将会是类似"2021-07-01 12:30:00"这样的格式化日期字符串。 除了以上示例中的格式以外,还可以根据需要自行组合占位符来定义输出的日期格式。例如,可以使用"yyyy年MM月dd日 HH时mm分ss秒"来定义输出格式为"2021年07月01日 12时30分00秒"。 需要注意的是,Date.prototype.format()方法是自定义的方法,不是原生的JavaScript方法,所以在使用之前需要先定义该方法。 总而言之,使用Date.prototype.format()方法可以方便地格式化日期为指定的格式,提高日期处理的灵活性和可读性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值