-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters