You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何设置dayjs的默认日期格式化输出格式

dayjs设置默认格式化格式实现方案

你可以选择以下任意一种方案实现,无需每次调用format都重复写格式字符串:

  • 方案1:全局重写dayjs原型的format方法
    适合项目中所有dayjs调用都默认使用该格式的场景,在项目全局初始化dayjs的入口位置写入以下逻辑即可:

    import dayjs from 'dayjs'
    // 缓存原生format方法
    const originFormat = dayjs.prototype.format
    // 重写format,设置默认入参为目标格式
    dayjs.prototype.format = function (pattern = 'YYYY-MM-DD HH:mm:ss') {
      return originFormat.call(this, pattern)
    }
    

    配置完成后,调用format()不传参就会默认按YYYY-MM-DD HH:mm:ss输出,如果你需要特殊格式,正常传入格式字符串即可,不会被默认值影响:

    // 以下写法都能正常输出目标格式
    this.dayjs().startOf("year").format()
    this.dayjs().format()
    this.dayjs().startOf("week").format()
    // 需要其他格式时正常传参,不受默认配置影响
    this.dayjs().format("YYYY年MM月DD日")
    

    注意:如果你注册了advancedFormat这类修改format逻辑的插件,需要把上述重写逻辑放在插件注册代码之后执行,避免插件逻辑被覆盖。

  • 方案2:二次封装自定义dayjs方法
    如果你不想修改dayjs原生原型的默认行为,可以自己封装一层dayjs工具方法,项目中所有用到dayjs的位置统一引用封装后的方法:

    // 新建 src/utils/dayjs.js 作为统一引用入口
    import dayjs from 'dayjs'
    
    const myDayjs = function (...configs) {
      const instance = dayjs(...configs)
      const originFormat = instance.format
      instance.format = function (pattern = 'YYYY-MM-DD HH:mm:ss') {
        return originFormat.call(this, pattern)
      }
      return instance
    }
    // 透传dayjs原生的所有静态属性、插件方法
    Object.keys(dayjs).forEach(key => {
      myDayjs[key] = dayjs[key]
    })
    
    export default myDayjs
    

    使用时把原来引入原生dayjs的位置改成引入你封装的myDayjs即可,调用逻辑和原生dayjs完全一致,不传format参数时默认走你配置的通用格式。

内容的提问来源于stack exchange,提问作者Crazy Cheese

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 10:45:59