My users could create some objects that have specific time and search them by query for specific startTime and endTime.
My question is how should I store these objects in my database (MongoDB)? Should I store them in UTC or with specific timezone that relates to user that create object?
Use UTC date format, and convert all data to UTC: when create, update, delete objects or filter them. Use one UTC time zone helps you avoid a lot of problems, and simplify you code.
> var now = new Date();
> Mon May 26 2014 10:55:34 GMT+0300 (Kaliningrad Standard Time)
> now.toUTCString();
> Mon, 26 May 2014 07:55:34 GMT
> new Date(now.toUTCString())
> Mon May 26 2014 10:55:34 GMT+0300 (Kaliningrad Standard Time)
When you create a new Javascript date object and assign it to a Mongo date field, it will automatically be usable with any timezone. If all you need is the current time, you can just use new Date()
. But if you need to take a string and have it be interpreted in a specific timezone, or you are going to be presenting a time to a user in a specific timezone, I highly recommend checking out Moment Timezone.
This code will take a date object stored in a Mongo model (which could be 1AM on January 1, 2014 in Sydney, Australia) and present it formatted to a Los Angeles timezone (which would still be December 31, 2013).
collection.find({_id: 123}, function(err, model) {
userDate = moment(model.date).tz("America/Los_Angeles").format("MM/DD/YYYY");
});
And if you ever need to parse a string that doesn't specify a UTC offset as a specific timezone, you can use the constructor:
moment.tz("2013-11-18 11:55", "America/Toronto")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With