Patterns for working with time in JS


This is a general question not related to Meteor but to more general JS/programming.
Do you have patterns you have found to work great when working with time ?
I’m currently writing time as a “hour” and a “minute” numbers in mongo, then transforming them upon loading in an HM object {hour: XXX, minute: XXX}. Sometimes i convert my hour/minute in pure minutes, making manipulation easier (hence 10 hours 30 minutes becomes 630).
Depending on use i’m constantly converting between these three formats, which is ugly, and the source of many bugs.
What are you guys doing ?


I handle all my time and date stuff with



moment().add(7, 'days').subtract(1, 'months').year(2009).hours(0).minutes(0).seconds(0);


moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"


Presuming you’re on Meteor 1.3 following the guide for your application structure,

Run the following from your project folder

meteor npm install moment --save

And add this to the top of the .js files in /imports/ where you need it

import moment from 'moment';

The NPM ecosystem being readily availble for Meteor is great in general for other low level problems as well.


Thank you all for your pointers to moment, which i already use.
But what is your format of choice in the database ? Vanilla JS Date object ?


Yeah I use vanilla JS date objects in the database.


I tend to store time as unix time or seconds if it’s a duration. I tend to find it’s the easiest to work with over a variety of systems. In JS I then use momentjs to convert it to whatever I need.


Another thing that might be relevant in certain cases: don’t forget to account for the server and client being set in different timezones.

For example, if you wanted to build a query like “show me all posts published on Friday, May 20th” it could very well give different results on client and server (which would then lead to all kinds of weird pub/sub issues).