Do not serialize new Date(undefined) as "0NaN-NaN-NaNTNaN:NaN:NaN.NaN+NaN:NaN"
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").
@charmander https://github.com/brianc/node-postgres/pull/3326
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"));