I want to serialize and deserialize dates using a custom format. For that, I’m trying to intercept the date during JSON.stringify() using a custom receiver
function serialize(data) {
if (data === undefined) {
return JSON.stringify('__undef__')
}
if (data instanceof Date) {
return JSON.stringify({ _t: 'dt', v: data.getTime() })
}
return JSON.stringify(data, (_, value) => {
if (value === undefined) {
return '__undef__'
}
if (value instanceof Date) {
return { _t: 'dt', v: value.getTime() }
}
return value
})
}
console.log(serialize(new Date(2024, 7, 4))); // {"_t":"dt","v":1722729600000}
console.log(serialize([undefined, new Date(2024, 7, 4)])); // ["__undef__","2024-08-04T00:00:00.000Z"]
Seems like the receiver is not intercepting the date format before serialization.
What am I doing wrong?