Issue with Date.now()

276 views
Skip to first unread message

Aman Passi

unread,
Oct 25, 2018, 11:04:18 PM10/25/18
to mongodb-user
Hi All- one of the developer is using  below to insert record into mongo db to capture the default timestamp.
  timestamp: { type: Date, default: moment.utc(Date.now()) } // timestamp using Default MONGODB
But whenever the date/time is inserted its off.
The mongo version running is:-3.6.3
Any thoughts ?

Thanks,
Aman

ABHISHEK SINGH Solanki

unread,
Oct 30, 2018, 8:53:31 PM10/30/18
to mongodb-user
Hi Aman,

If you want you can use new Date() function to insert the current datetime of mongo server's time zone.

example:- db.collection.createOne({"timestamp": new Date()})

Kevin Adistambha

unread,
Nov 1, 2018, 11:52:07 PM11/1/18
to mongodb-user

Hi Aman,

But whenever the date/time is inserted its off.

Could you specify what you mean by “off” in this context?

If I understand correctly, you’re trying to insert the current datetime into a document. However, Date.now() will give you the client’s datetime instead of the servers. Also, moment.utc(Date.now()) does not return a date object as understood by MongoDB. Rather, it will return a moment object. I believe what you want is similar to:

timestamp: { type: Date, default: new Date(moment.utc(Date.now())) }

The new Date(...) will convert the moment object into a MongoDB Date object which can then be recognized by MongoDB, e.g. for use in TTL index.

MongoDB store dates in UTC by default.

If you want you can use new Date() function to insert the current datetime of mongo server’s time zone.

Actually it will insert the client’s time instead of the server’s time. This is because the expression new Date() was evaluated client-side (since it’s a Javascript expression) before it was sent to the server.

Best regards,
Kevin

Reply all
Reply to author
Forward
0 new messages