I am trying to find all users that have a matching birthday stored in the format "1975-01-12T00:00:00.000+00:00"
When I send a date of type String to my route and convert it to a date with new Date(req.body.DOB) I am getting a date with an additional 4 hours: "1975-01-12T04:00:00.000Z" and a Z at the end.
I am new with dates so not too sure what is going on. How can I convert the string date into a date in the same way it is saved in my database, without the additional 4 hours and Z?
router.post("/api/date", async (req, res) => {
try {
const birthdate = new Date(req.body.DOB) // String as "01-12-1975"
const users = await User.find({
DOB: birthdate,
})
res.status(200).send(users)
} catch (err) {
res.status(400).send()
}
})
Databases typically use iso_8601 date format, which includes timezone. Javascript dates use the system timezone upon instantiation, if you use a format which omits the timezone (like the one you have). This is why there is an offset of 4 (offset from UTC timezone), presumably your server is in Russia or something.
You should convert the string to ISO format before converting to a date object. For example, if you store all birthdays as UTC time (at midnight), then you can just convert it like so:
const dateStr = "01-12-1975"
const [date, month, year] = dateStr.split('-')
const isoStr = `${year}-${month}-${date}T00:00:00.000Z`
const newDate = new Date(isoStr) // 1975-12-01T00:00:00.000Z