Skip to content

Commit

Permalink
feat(formatDate): 渲染器支持字符串
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Sep 23, 2021
1 parent c6e2659 commit 431b16e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
29 changes: 28 additions & 1 deletion src/date/formatDate.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { formatDate } from './formatDate'

describe(formatDate.name, () => {
describe('formatDate', () => {
test('格式化正常', () => {
expect(
formatDate(
Expand Down Expand Up @@ -30,4 +30,31 @@ describe(formatDate.name, () => {
),
).toBe('2020年05月20日13时45分08秒')
})

test('渲染器为字符串时格式化正常', () => {
expect(
formatDate(new Date(2020, 5 - 1, 20, 13, 45, 8), 'y年m月d日h时i分s秒'),
).toBe('2020年5月20日13时45分8秒')

expect(
formatDate(
new Date(2020, 5 - 1, 20, 13, 45, 8),
'yyyy年mm月dd日hh时ii分ss秒',
),
).toBe('2020年05月20日13时45分08秒')

expect(
formatDate(
new Date(2020, 5 - 1, 20, 13, 45, 8).getTime(),
'yyyy年mm月dd日hh时ii分ss秒',
),
).toBe('2020年05月20日13时45分08秒')

expect(
formatDate(
Math.round(new Date(2020, 5 - 1, 20, 13, 45, 8).getTime() / 1000),
'yyyy年mm月dd日hh时ii分ss秒',
),
).toBe('2020年05月20日13时45分08秒')
})
})
13 changes: 9 additions & 4 deletions src/date/formatDate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ export enum FormatDatePlaceholder {
* @param placeholders 占位符
* @returns 返回渲染字符串
*/
export type FormatDateRenderer = (
placeholders: typeof FormatDatePlaceholder,
) => string
export type FormatDateRenderer =
| ((placeholders: typeof FormatDatePlaceholder) => string)
| string

/**
* 格式化日期。
Expand All @@ -98,5 +98,10 @@ export function formatDate(date: Date | number, renderer: FormatDateRenderer) {
date *= 1000
}

return lightFormat(date, renderer(FormatDatePlaceholder))
return lightFormat(
date,
typeof renderer === 'string'
? renderer.replace(/m/g, 'M').replace(/h/g, 'H').replace(/i/g, 'm')
: renderer(FormatDatePlaceholder),
)
}

0 comments on commit 431b16e

Please sign in to comment.