Save date of birth of user without timezone

Hi All,

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) };
const mongoose = require('mongoose');

let UserSchema = new mongoose.Schema({
	dob: Date,
});

run().catch((err) => console.log(err));

async function run() {
	await mongoose.connect('mongodb://localhost:27017/test', {
		useNewUrlParser: true,
		useUnifiedTopology: true,
	});
	await mongoose.connection.dropDatabase();

	const UserModel = mongoose.model('user', UserSchema);

	const newUser = { dob: '10/16/1995' };
	const user = new UserModel(newUser);
	await user.save();
	console.log(user, 'output');

	// output
	/* { _id: 5f5f13e643f6c0cc94ab26a8,
  dob: 1995-10-15T18:30:00.000Z,
  __v: 0 } '' */
}

Add a Z to the date to indicate it is already UTC:

> db.test.insertOne( { dob: new Date('10/16/1995Z') })
{
	"acknowledged" : true,
	"insertedId" : ObjectId("5f608deee83a779d9f5a4412")
}
> db.test.findOne()
{
	"_id" : ObjectId("5f608db5e83a779d9f5a4411"),
	"dob" : ISODate("1995-10-15T23:00:00Z")
}
>

Hi Joe,

Why i am seeing different result than yours, as we marking that it is already UTC.

image

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.

Thank you for quick response.

Hi Joe,

Above highlight is wrong, Here is the correct output that i am getting

image strong text

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.

> db.test.drop()
true
> db.test.insertOne({dob: new Date("1/2/1964")})
{
	"acknowledged" : true,
	"insertedId" : ObjectId("5f6116f2e83a779d9f5a441b")
}
> db.test.find()
{ "_id" : ObjectId("5f6116f2e83a779d9f5a441b"), "dob" : ISODate("1964-01-02T00:00:00Z") }
>

The trailing Z indicates UTC.

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

1 Like

insert a sample date in dateTest collections.

db.dateTest.insert(
{
“_id” : 1,
“date” : ISODate(“2020-09-16T09:55:39.736Z”)
}
)

Here is the query:

db.dateTest.aggregate(
[
{
$project: {
dateOnly: { $dateToString: { format: “%Y-%m-%d”, date: “$date” } },
}
}
]
)

and this will be the output:

/* 1 */
{
“_id” : 1.0,
“dateOnly” : “2020-09-16”
}

Hope so this will help you out, if so then kindly mark this as Solution. Thanks

but if you insert without time, it does not add 00 instead of UTC timezone as you can see in above post

Hi Joe,

This does not make date to fixed i think i should save as string instead type date
image

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.

4 Likes

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

1 Like

Thank you Joe, This works so great!

i appreciate your help for quick response.

<3 Mongodb

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.