What is the best way to store dates in MongoDB?

I’m actually in the process of converting a MongoDB database where dates are stored as proper Date() types to instead store them as strings in the form yyyy-mm-dd. Why, considering that every other answerer says that this is a horrible idea? Simply put, because of the neverending pain I’ve been suffering trying to work with dates in JavaScript, which has no (real) concept of timezones. I had been storing UTC dates in MongoDB, i.e. a Date() object with my desired date and the time set as midnight UTC, but it’s unexpectedly complicated and error-prone to get a user-submitted date correctly converted to that from whatever timezone they happen to be in. I’ve been struggling to get my JavaScript “whatever local timezone to UTC” code to work (and yes, I’m aware of Sugar.js and Moment.js) and I’ve decided that simple strings like the good old MySQL standard yyyy-mm-dd is the way to go, and I’ll parse into Date() objects as needed at runtime on the client side.

Incidentally, I’m also trying to sync this MongoDB database with a FileMaker database, which also has no concept of timezones. For me the simplicity of simply not storing time data, especially when it’s meaningless like UTC midnight, helps ensure less-buggy code even if I have to parse to and from the string dates now and then.

Leave a Comment