0

Folks, Which should I use for storing timestamps? I currently have an API service that i am writing, which stores timestamps in MongoDB. These timestamps are important to me, as I will need to then query the database on time ranges... ie return all documents which were stored in the past hour, or between certain dates.

IOS app sends me objects with the following timestamps in ISO8601:

2014-10-09T18:00:48+01:00

If i store these straight into mongo, document looks like:

{
    "_id" : "2B6127C1-4E25-4271-B5A4-2CA9FEA4E1C3",
    "timestamp" : "2014-10-09T18:00:48+01:00"
}

I can easily insert this into mongo, but it seems to me that I should do object.timestamp = moment(object.created).toDate();

Which would yield:

2014-10-09T18:00:48+01:00

and the document would look like this in mongo:

{
    "_id" : "2B6127C1-4E25-4271-B5A4-2CA9FEA4E1C3",
    "timestamp" : ISODate("2014-10-09T13:00:48.000-04:00")
}

Should i convert these into unix epoch format? I am not very versed on differences of ISO timestamp formats... I think in the first example, IOS sends me a ISO8601 format timestamp. Is this industry standard?

I have read several threads, including Best way to store date/time in mongodb , and it seems to me I am on the right track to convert the timestamp i get from ios into native javascript date object.

When users retrieve these objects, should I then transform this stored object into ISO8601 format?

Community
  • 1
  • 1
Cmag
  • 14,946
  • 25
  • 89
  • 140

1 Answers1

1

Storing in the most native format will let you use more native functionality. Mongo's query or aggregation API can use $gt or $lte with a native date. Which is really handy for querying. It is much harder to do those types of things with "strings that represent dates".

Storing in milliseconds from 1970, or whatever, works kind of the same way, but since ISODate is a type recognized by Mongo, just use it.

Also, nice pick on moment.js. That's a fun library, and makes whatever you choose to show to your client hidden from how the data is stored (which is how you want it...).

clay
  • 5,917
  • 2
  • 23
  • 21
  • perfect! on the way out, i'll transform the timestamp into `iso8601` for ios :) – Cmag Oct 13 '14 at 16:46
  • Im having a horrible time converting the local timestamp to utc timestamp :( Maybe you can help! http://stackoverflow.com/questions/26873200/momentjs-getting-javascript-date-in-utc – Cmag Nov 11 '14 at 20:20