Skip to content

Commit

Permalink
feat(useDateFormat): add format (#1491)
Browse files Browse the repository at this point in the history
  • Loading branch information
blackhu0804 committed Apr 14, 2022
1 parent 82eef26 commit a9c800d
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/shared/useDateFormat/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Get the formatted date according to the string of tokens passed in, inspired by
| `s` | 0-59 | The second |
| `ss` | 00-59 | The second, 2-digits |
| `SSS` | 000-999 | The millisecond, 3-digits |
| `d` | 0-6 | The day of the week, with Sunday as 0 |

## Usage

Expand Down
3 changes: 3 additions & 0 deletions packages/shared/useDateFormat/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,7 @@ describe('useDateFormat', () => {
it('should work with HH:mm:ss:SSS', () => {
expect(useDateFormat(new Date('2022-01-01 15:05:05:999'), 'HH:mm:ss:SSS').value).toBe('15:05:05:999')
})
it('should work with HH:mm:ss d', () => {
expect(useDateFormat(new Date('2022-01-01 15:05:05'), 'HH:mm:ss d').value).toBe('15:05:05 6')
})
})
2 changes: 2 additions & 0 deletions packages/shared/useDateFormat/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export const formatDate = (date: Date, formatStr: string) => {
const minutes = date.getMinutes()
const seconds = date.getSeconds()
const milliseconds = date.getMilliseconds()
const day = date.getDay()
const matches: Record<string, string|number> = {
YY: String(years).slice(-2),
YYYY: years,
Expand All @@ -30,6 +31,7 @@ export const formatDate = (date: Date, formatStr: string) => {
s: String(seconds),
ss: `${seconds}`.padStart(2, '0'),
SSS: `${milliseconds}`.padStart(3, '0'),
d: day,
}
return formatStr.replace(REGEX_FORMAT, (match, $1) => $1 || matches[match])
}
Expand Down

0 comments on commit a9c800d

Please sign in to comment.