DEV Community

Nisa JThani
Nisa JThani

Posted on

What can cause `new Date()` to return incorrect dates?

I am trying to solve a problem in which I have found date values in my MongoDB database to be inaccurate.

For example, in my database, I have a list of tokens that are set to be deleted by the database 12 hours after they're created. I noticed some of my tokens were missing so I disabled the expiration function. It turns out some of these tokens have inaccurate creation dates. The worst case was a token that was created on June 25th but has an creation date value of '2020-06-03T09:00:29.506+00:00'. That's a 22 day difference!

I use JavaScript's new Date() method to create the dates. MongoDB by default will convert a date object created by JavaScript's new Date() to UTC.

I have ensured my system's built-in time synchronization is activated. What else can I do to make new Date() return correct dates?

Top comments (2)

Collapse
 
gdsoumya profile image
Soumya Ghosh Dastidar

I don't exactly know what's wrong with your code without seeing it completely. Just some tips :

  1. Always set the Date on the server and not from the client side.
  2. Use unix timestamp for easier calculations, they can be easily converted to any date-time format.
Collapse
 
nisajthani profile image
Nisa JThani

Thank you for your reply.

  1. The Date is already set on my Node.js LoopBack 4 server
  2. I haven't tried this method. I will do this next. Thanks.