I just want a confirmation from the experts. I still don't feel confident in what I believe to be the right way of storing and treating dates in such environment.
I'm developing a little app, just for italian users.
Basically, they can create a list of entries, each having a creationDate (I am just interested in the date part, time is not useful in my scenario).
So, the user enters in the "date" form field a date in this format: 22/06/2014 represents the 22th day of June of year 2014. Then, date is parsed like that:
entryData.dateEntry = moment( $(form).find('input[name=dateEntry]').val(), 'DD-MM-YYYY' ).toDate();
Finally, my entry model is added to a backbone.js collection and stored server-side by Node.js + Express in MongoDB.
Querying Mongo for entries, I see:
2014-06-21 22:00:00 +0000
which corresponds to "dateEntry" : Date( 1403388000000 ).
Googling around, I discovered that MongoDB doesn't have the concept of timezone. All dates are stored in UTC and the date object I created before had GMT+2. But I'm really scared... how will I get back my local timezone's date the easy way?
Next, I'll display entry data in an underscore template, this way:
<%= moment(dateEntry).format('DD/MM/YYYY') %>
And... voilà! I get my local 'italian' date back: 22/06/2014.
Now, my question: is that the right way to go?
The process is: parse dates in local timezone => store in utc => retrieve dates in local timezone. Is it a common practice?
I also thought: can't I simply avoid using timezones and storing my local (italian) time as it was utc time (2014-06-22 00:00:00)? Is that so bad?
Yes, it's a common practise to store all timestamps in UTC, and then convert it to specific timezones in the outer layers. A lot of frameworks automatically do that for you, including Rails. Let's say if going forward you start catering to other timezones as well, you will not face any problems because your DB has UTC entries. You will be saved the overhead of timezone conversions.
In case you want to save only dates, you can do that as well, but I don't see any harm in the way you do it currently - save everything in UTC. I am not sure about node.js but there would be some setting where you can specify the timezone (of Italy), and all your conversions will happen automatically. You may find this thread useful:
How can I set the default timezone in node.js?
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