Skip to content

Commit

Permalink
feat(date): 新增 anyToDate
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jul 8, 2020
1 parent dd0c1ae commit 06d502c
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/date/anyToDate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { anyToDate } from './anyToDate'

describe('anyToDate', () => {
test('表现正常', () => {
const now = new Date()

expect(anyToDate(now.getTime())).toEqual(now)
expect(anyToDate(Math.round(now.getTime() / 1000))).toEqual(
(() => {
const _now = new Date(now)
_now.setMilliseconds(0)
return _now
})(),
)

expect(anyToDate(String(now.getTime()))).toEqual(now)
expect(anyToDate(String(Math.round(now.getTime() / 1000)))).toEqual(
(() => {
const _now = new Date(now)
_now.setMilliseconds(0)
return _now
})(),
)

expect(anyToDate(now.toISOString())).toEqual(now)

expect(anyToDate(now)).toEqual(now)
})
})
25 changes: 25 additions & 0 deletions src/date/anyToDate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { isNumeric } from '../utils'
import { parseISO, toDate } from 'date-fns/esm'

/**
* 增强版的 toDate,支持:
* - 秒时间戳、毫秒时间戳;
* - Date 实例;
* - 符合 ISO 标准的时间字符串。
*
* @param value 要转换的值
* @returns 返回转换后的 Date 实例
*/
export function anyToDate(value: string | number | Date): Date {
if (typeof value === 'string') {
if (isNumeric(value)) {
value = Number(value)
} else {
value = parseISO(value)
}
}
if (typeof value === 'number' && String(value).length === 10) {
value *= 1000
}
return toDate(value)
}
1 change: 1 addition & 0 deletions src/date/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,7 @@ export {
} from 'date-fns/esm/locale'

// @index(['./**/*.ts', '!./**/*.test.*'], f => `export * from '${f.path}'`)
export * from './anyToDate'
export * from './formatDate'
export * from './numeralDayToChineseDay'
// @endindex

0 comments on commit 06d502c

Please sign in to comment.