luxon icon indicating copy to clipboard operation
luxon copied to clipboard

DateTime's toJSON and Nullish Coalescing

Open bnb opened this issue 3 years ago • 1 comments

Describe the bug If you JSON.stringify() an object with a DateTime that's nullish coalesced, you can actually get null returned because of how luxon overrides toJSON since toJSON will return NaN which gets swapped to null when stringifying.

To Reproduce Here's the cut down reproduction (but not totally minimal!) of how I found this: https://github.com/bnb/nc-test

You can see each step of the logic output in output.txt.

Actual vs Expected behavior I should be able to ?? a DateTime and then subsequently JSON.stringify() it and not get null.

Desktop (please complete the following information):

  • OS: Ubuntu in WSL2
  • Luxon version: 2.3.0
  • Your timezone: America/New_York

bnb avatar Feb 24 '22 18:02 bnb

I suspect the problem is the DateTime object is invalid, which causes the NaN:

let dt = luxon.DateTime.now();
JSON.stringify({dt: dt ?? undefined}) //=> '{"dt":"2022-02-24T14:16:01.672-05:00"}'

dt = luxon.DateTime.invalid("not a valid datetime")
JSON.stringify({dt: dt ?? undefined}) //=> '{"dt":null}'

Invalid state is annoying in general and I'd like to remove it in the next version of Luxon, but in the meantime, it's hard to imagine how else we'd serialize it.

icambron avatar Feb 24 '22 19:02 icambron