js 日期转换格式

js 日期转换格式

/**

  • 日期转换格式

  • @param date 当前时间,new Date() 格式

  • @param format 时间格式字符串

  • @description format 如 yy-mm、y-m-dd

  • @returns 时间
    */
    function formatDate2(date: Date, format: string): string {

    //opt的key带了 “+” 号,表示正则要匹配多次,例如输入format格式输入y 或者 yyy 都会被匹配到
    const opt = {
    ‘y+’: date.getFullYear().toString(), // 年
    ‘m+’: (date.getMonth() + 1).toString(), // 月(月份从0开始)
    ‘d+’: date.getDate().toString(), // 日
    ‘H+’: date.getHours().toString(), // 时
    ‘M+’: date.getMinutes().toString(), // 分
    ‘S+’: date.getSeconds().toString(), // 秒
    };

    for (let k in opt) {
    let r = new RegExp(‘(’ + k + ‘)’).exec(format);
    if®{
    //如果值小于10,则 添加0,例如 09月
    if(Number(opt[k])<10){
    opt[k] = “0”+ opt[k]
    }
    //替换格式里面的值
    format = format.replace(r[1], opt[k])
    }
    }
    return format;
    }

console.log(“1–”,formatDate2(new Date(), “yy-mm”))
console.log(“2–”,formatDate2(new Date(), “y-m”))
console.log(“3–”,formatDate2(new Date(), “y__m__d H:M:S”))
console.log(“4–”,formatDate2(new Date(), “yyy-mm-dd HH:MM:SS”))

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值