javascriptvue.jsdayjs

How to set the default format in dayjs?


I want set "YYYY-MM-DD HH:mm:ss" to the default format to avoid unnecessary code like:

this.dayjs().startOf("year").format("YYYY-MM-DD HH:mm:ss")
this.dayjs().format("YYYY-MM-DD HH:mm:ss")
this.dayjs().startOf("week").format("YYYY-MM-DD HH:mm:ss")

Can anyone give me some advice?


Solution

  • Found a way, by overwriting the default format method in a plugin:

    const defaultFormat = 'YYYY-MM-DD HH:mm:ss'
    
    dayjs.extend((option, dayjsClass, dayjsFactory) => {
      const oldFormat = dayjsClass.prototype.format
    
      dayjsClass.prototype.format = function (formatString) {
        return oldFormat.bind(this)(formatString ?? defaultFormat)
      }
    })
    

    Modified example from https://day.js.org/docs/en/plugin/plugin

    After using this plugin the custom default format will now be applied when you call .format() without any parameters.