I'm using fetch
to send a date to the server. This should be an exact date (no time) because the server uses Java LocalDate
there.
In my timezone a date like 2020-01-01 is stringified to 2019-12-31T23:00:00.000Z
. The server then drops the time part. When converting to LocalDate
, it doesn't know what timezone I'm in, I could be anywhere.
So I resorted to overriding Date.prototype.toJSON
by a function that moves the date to UTC so that it is stringified as 2020-01-01T00:00:00.000Z
. This is of course very ugly but at least it works.
Then I thought, let's override toJSON
right before the request and reset it after the request returns. But whatever I tried (additional promises, timeouts), fetch
uses the native toJSON
. So this doesn't work:
Date.prototype.toJSON = function () {
return ... // Date moved to UTC. This works when set when the page loads.
}
const response = await fetch(...) // Fetch uses the native toJSON
// Setting a breakpoint here reveals that toJSON is my version as expected. But fetch didn't use it.
Date.prototype.toJSON = toJSON // Reset back to native
I read up on tasks and microtasks but found nothing that could explain this.
I also found no one with the same issue, so I'm probably going about this the wrong way.
So my questions:
- How do I send a date in any time zone to the server such that it is properly converted to a
LocalDate
(other than globally overridingtoJSON
)? - How does
fetch
use the nativetoJSON
if it is overridden right before? Just so I understand what is happening. - The server is built using the Micronaut framework, is there something we could change there? I can't think of anything but who knows.