事情是这样的,今天后端给回了个221021格式的字符串,要我同事在前端转为DDMMMYYYY格式。
他问我怎么转,我反手抛出了一个
dayjs('221021','DDMMYY').format('DDMMMYYYY')
欸,他一试,反手打我脸。
后来查了一下资料和源码,算是找到了原因,特此记录一下。
查找流程
上面代码的运算结果是:
01Sep2211
当时看到这个结果,我一冲动就跑github下了dayjs的源码(没先看文档)
https://github.com/iamkun/dayjs
在src/index.js中,很快就能定位到31行的dayjs方法:
const dayjs = function (date, c) {
if (isDayjs(date)) {
return date.clone()
}
// eslint-disable-next-line no-nested-ternary
const cfg = typeof c === 'object' ? c : {}
cfg.date = date
cfg.args = arguments// eslint-disable-line prefer-rest-params
return new Dayjs(cfg) // eslint-disable-line no-use-before-define
}
然后顺着找到Dayjs对象:
class Dayjs {
constructor(cfg) {
this.$L = parseLocale(cfg.locale, null, true)
this.parse(cfg) // for plugin
}
...
在构造函数中找到了 this.parse(cfg) 方法的调用,
接着便是主要的parseDate方法。
const parseDate = (cfg) => {
const { date, utc } = cfg
if (date === null) return new Date(NaN) // null is invalid
if (Utils.u(date)) return new Date() // today
if (date instanceof Date) return new Date(date)
if (typeof date === 'string' && !/Z$/i.test(date)) {
const d = date.match(C.REGEX_PARSE)
if