node-postgres icon indicating copy to clipboard operation
node-postgres copied to clipboard

Do not serialize new Date(undefined) as "0NaN-NaN-NaNTNaN:NaN:NaN.NaN+NaN:NaN"

Open ikonst opened this issue 1 year ago • 2 comments

Currently new Date(undefined) (an invalid date) is serialized as "0NaN-NaN-NaNTNaN:NaN:NaN.NaN+NaN:NaN" which is not parsed by Postgres in any meaningful way.

We can either fail early by throwing a JS error, or produce a Postgres value that more obviously indicates an invalid date (e.g. "Invalid date").

ikonst avatar Sep 20 '24 10:09 ikonst

@charmander https://github.com/brianc/node-postgres/pull/3326

abbas-ramish avatar Oct 05 '24 08:10 abbas-ramish

The behavior you're describing—where new Date(undefined) produces an invalid date is quirk. When you pass undefined, it tries to create a date from undefined, resulting in an Invalid Date object. However, when serialized (e.g., converted to a string), it can lead to unexpected results, like the strange "0NaN-NaN-NaNTNaN:NaN:NaN.NaN+NaN:NaN" output you observed.

To address this, the best practice would be to add validation logic that explicitly checks for invalid inputs to new Date() and throws an error early if the input is invalid. If you'd prefer the function to return a fallback value instead of throwing errors, you could use this approach:

function safeCreateDate(input) { const date = new Date(input); return isNaN(date.getTime()) ? null : date; }

console.log(safeCreateDate(undefined)); console.log(safeCreateDate("2024-11-19"));

itisrajeevsingh avatar Nov 21 '24 09:11 itisrajeevsingh