I want to fire a query to get person whose date of birth is matched to current date

I am comparing person date of birth which is stored as UTC format by client side with current date at 00:00 on time zone asia/kolkata, but it gives me the previous previous date data. I mean at 00:00:00 at 17-mar-2021 i fired the query, It should check that is there any entries whose date and month in date of birth matches to 17 of March? But it compares with 16 of march, I don’t figure out why this is happening.

Query

const userFound = await Contact.find({
  $expr: {
    $and: [
      { $eq: [{ $dayOfMonth: '$dob' }, { $dayOfMonth: new Date() }] },
      { $eq: [{ $month: '$dob' }, { $month: new Date() }] },
    ],
  },
});

Here, dob stores the data of birth of person in UTC format (e.g. ‘2021-03-17T00:00:00.000+00:00’) .
Also I have tried it in morning its work fine, But at 00:00:00 it won’t. Why it is happening and what its solution?

The issue is that it won’t give you the response you want until you wait till it’s after midnight in UTC. When you are querying it right after midnight in Kolkata, it’s actually still the previous day in UTC and it’s correct that those records are not being returned.

There are a few ways you can correct this - easiest would be to query against stored date converted into your local timezone.

Starting with 3.6 both $dayOfMonth and $month accept an optional timezone argument. This should allow you to compare the two dates in the same “context”.

Asya

1 Like