iamkun / iamkun/dayjs

`dayjs.tz()` throws when parsing invalid date string

Open
#1,637 3 comments 11 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
48.7k
Forks
2.5k
PR merge metrics
No merged PRs in 30d

Description

**Describe the bug**
The behavior when parsing an invalid date string differs between `dayjs(...)`, which returns an invalid date, and `dayjs.tz(...)`, which throws `RangeError: invalid time value`.

Code [(available in CodeSandbox)](https://codesandbox.io/s/charming-perlman-bvl37?file=/src/index.tsx:0-268):
```ts
import dayjs from "dayjs";
import dayjs_utc from "dayjs/plugin/utc";
import dayjs_timezone from "dayjs/plugin/timezone";

dayjs.extend(dayjs_utc);
dayjs.extend(dayjs_timezone);

console.log("Test 1", dayjs(""));
console.log("Test 2", dayjs.tz("", "America/New_York"));
```

Output:
```text
Test 1 M {$L: 'en', $d: Invalid Date, $x: {…}, $y: NaN, $M: NaN, …}
index.js:27 Error in sandbox:
index.js:27 RangeError: Invalid time value
at DateTimeFormat.formatToParts ()
at a (eval at J (eval.js:31), :1:770)
at u (eval at J (eval.js:31), :1:814)
at eval (eval at J (eval.js:31), :1:1888)
at Function.o.tz (eval at J (eval.js:31), :1:2001)
at $csb$eval (VM737 index.tsx:16)
at J (eval.js:31)
at ee.evaluate (transpiled-module.js:709)
at xe.evaluateTranspiledModule (manager.js:334)
at xe.evaluateModule (manager.js:305)
at compile.ts:724
at c (runtime.js:45)
at Generator._invoke (runtime.js:274)
at Generator.forEach.t. [as next] (runtime.js:97)
at r (asyncToGenerator.js:3)
at u (asyncToGenerator.js:25)
```

**Expected behavior**
`dayjs("")` and `dayjs.tz("", "America/New_York")` should behave the same way. They should both return a dayjs object such that `isValid() == false`.

**Information**
- Day.js Version: 1.10.7
- OS: Windows 10
- Browser: Chrome 93
- Time zone: GMT-04:00 DST (Eastern Daylight Time)

Contributor guide

Open the contributing guide

Research direction

Reproduce the issue using the provided dayjs.utc and dayjs.timezone plugin setup and the empty-string calls shown in the report. Start at the timezone plugin's dayjs.tz entry point; done means invalid input no longer throws and both calls return objects for which isValid() is false.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
api
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.