Feature Request - dayjs.safeParse() for safe parsing, especially for strings
- Dominant language
- JavaScript
- Stars
- 48.7k
- Forks
- 2.5k
- PR merge metrics
- No merged PRs in 30d
Description
My idea is,
```typescript
function safeParse (s: any): Dayjs {
if (typeof s === 'string') {
let m: RegExpExecArray | null = null
if (typeof s !== 'string') {
throw new Error(`Not a string: ${s} -- ${typeof s}`)
}
if (m = /(\d{4})(\d{2})(\d{2})?/.exec(s)) {
return dayjs(`${m[1].padStart(2, '0')}-${m[2].padStart(2, '0')}-${(m[3] || '1').padStart(2, '0')}`)
}
if (/[-+]?(?:\d+(?:\.\d+)?|\.\d+)/.test(s)) {
throw new Error(`Is an invalid Number string: ${s}`)
}
return dayjs(s)
}
...
}
```
Actually, I have already implemented this, with testing, here. -- https://github.com/patarapolw/q2object/tree/master/packages/is-datestring
```
Is a valid Number string
✓ '20190101'
✓ '201902'
Is an invalid Number string
✓ '1'
✓ '0'
✓ '-1'
✓ '1.1'
✓ '0.1'
✓ '.1'
✓ '-.1'
Not a string
✓ 1
✓ true
✓ null
✓ ! ''
✓ ! 'function () { }'
✓ 2020-01-07T18:24:03.053Z
```
Contributor guide
Assessment
This issue has not been assessed yet.