Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store datetime on server side in nodejs?

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?

like image 242
Erik Avatar asked May 26 '14 07:05

Erik


2 Answers

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.

example

> 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)
like image 122
Nikolay Lukyanchuk Avatar answered Oct 17 '22 02:10

Nikolay Lukyanchuk


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")
like image 29
Ted Avery Avatar answered Oct 17 '22 03:10

Ted Avery