how do you save date of birth of user, It is changing due to timezone.It is returning minus one i.e if you pass 16 date it returns 15, if you pass 18 date it returns 17.
Also i tried with new Date() but still it returns less than one
const newUser = { dob: new Date('10/16/1995') };
const user = new UserModel(newUser);
await user.save();
Also i converted date into yyyy-mm-dd but still same
let date = '2/10/1977';
date = new Date(
`${date.split('/')[2]}-${date.split('/')[0]}-${date.split('/')[1]}`,
);
console.log(date);
const newUser = { dob: new Date(date) };
Why i am seeing different result than yours, as we marking that it is already UTC.
I am very curious in your output you are getting 15 and i get 16 where as i want 16 always since it is DOB. I don’t find any good docs related to manage date with mongodb.
Apologies my first example was in error. So just appending a Z to a raw date causes it to fail to parse and date and instead it uses the epoch date hence the 1970 date. To use the Z suffix you need a date and a time.
You can just insert a constructed date without the Z and it will be added as UTC by default.
if you want to get date in this format (10/16/1995) then i would recommend you to store them as a string. What’s the benefit of that… as you know mongodb stores the Date in ISO format so if we only insert the date(not the time) then it will ingest the timestamp as 00 with the date. so it’s better to use date as string. Hope so this will work for you.
Thanks
I think I worked out what is going on. The date you have specified is within your daylight savings period so the the hour is subtracted to create UTC forcing your date to be on the previous day. The fix is to specify the UTC date. e.g. :
> new Date("1977-04-01T00:00:00Z")
1977-04-01T00:00:00.000Z
> new Date("1977-04-01T00:00:00")
1977-03-31T23:00:00.000Z
>
The first date is reported correctly. The second date is shifted as it uses daylight savings time.
for that just insert a simple date it will store it to UTC format and i did the same i save it to ISOFormat and get the result in required form i.e. YYYY-MM-DD