Reputation: 319
In js file I have the variable
date=new Date()
which returns the current date correctly e.g.
date Thu Jan 30 2020 12:07:34 GMT+0200 (Eastern European Standard Time)
when calling the save method to insert the data in MongoDB
saveMethod:function(SessionId,date,methodName){
ExperimentData.insert({SessionId:SessionId, Date:date, MethodName:methodName})
return true;
},
I realize that the data field date is 2 hours before on the MongoDB, why does this happen?How can I save the correct current Date on the mongodb?
Upvotes: 0
Views: 50
Reputation: 8423
Mongo Dates are ISO date, which are always in UTC: https://docs.mongodb.com/manual/reference/method/Date/
Your local Date will however be relative to this date based on the local timezone settings. Thus there is no need to save the date explicitly different.
If you want to display the UTC date in your local time zone use toLocaleDate
:
const doc = MyCollection.findOne(docId)
const date = new Date(doc.Date)
console.log(date.toLocaleDateString()) // converted to locale
Upvotes: 0