Skip to content

Commit

Permalink
fix: date format
Browse files Browse the repository at this point in the history
  • Loading branch information
akijoey committed Feb 6, 2024
1 parent ef0b389 commit 4c5685f
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/extends/date.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
export const format = function format(
this: Date,
fmt = 'YYYY-MM-DDTHH:mm:ss.SSS'
) {
const options = {
'M+': this.getMonth() + 1,
'D+': this.getDate(),
'H+': this.getHours(),
'm+': this.getMinutes(),
's+': this.getSeconds(),
SSS: this.getMilliseconds()
}

const yearRegexp = /(Y+)/
if (yearRegexp.test(fmt)) {
fmt = fmt.replace(yearRegexp, match => {
return this.getFullYear().toString().slice(-match.length)
})
}

for (const [key, value] of Object.entries(options)) {
const regexp = new RegExp(`(${key})`)
if (regexp.test(fmt)) {
fmt = fmt.replace(regexp, match => {
return match.length === 1 ? value : value.toString().padStart(2, '0')
})
}
}

return fmt
}

export const install = (): void => {
Object.assign(Date.prototype, {
format
})
}

0 comments on commit 4c5685f

Please sign in to comment.