In the app, I am developing I have a date input
field.
I want to use it to search the appointments
collection on a specific date.
On the server, I am dealing with all dates in UTC
and this is how the search is going
const date = // date in iso sent from client
const startDate = new Date(date);
const endDate = new Date(date);
startDate.setUTCHours(0);
endDate.setUTCHours(24);
query.date = {
$gte: startDate,
$lt: endDate,
};
The problem is whenever I search for a date from an input
field some quirks are happening like
When I send to the date in ISO
some searches from one day before will appear depending on the hours of that appointment.
I tried to change the date like this date.setHours(0)
then send the ISO
string, the same thing happens only difference the problem shows up when the hour of the appointment is over 5 AM in UTC
what should I do in this case?
CodePudding user response:
It looks like it is happening because of the time offset. You can try adding the time offset difference to the UTC time. This might give you the desired result.
You can try something like this once you receive your date in ISO format.
19800 is the default value for TimeZone Offset in seconds for "Asia/Kolkata"
const newDate = new Date()
const serverOffset = newDate.getTimezoneOffset() * 60
const utcDifference = 19800 serverOffset
console.log(utcDifference);
You can use this UTCDifference to get your local time.
CodePudding user response:
I was able to resolve the issue by switching setUTCHours
to setHours
on the server
the problem was that I was changing the hour of the UTC
hour from the original date I have received which is making it fall behind for the offset difference so I am messing up the search dates so setting the locale hours gives the correct effect of searching between two dates and then mongoose already correctly searches the collection for desired dates.