neighbourhoodie-nnh-logo

How to Store Dates in CouchDB posted Wednesday, August 14, 2024 by The Neighbourhoodie Team

CouchDB uses JSON as a data format, and JSON does not have a built-in way to represent dates. But dates are commonly used when building applications for all sorts of things, and there are ways to store them in CouchDB, so how is that done?

The way to represent a specific date is called a timestamp and it can include calendar date info like year, month and day, as well as time like hours, minutes and seconds. Sometimes just date info is needed, sometimes just the time part, sometimes both are used together.

There are many many different types of timestamps, for example: “June 1st, 2020, 2:25pm” is a timestamp. So is 1591014378. They happen to convey about the same information.

This isn’t a full introduction into timestamps, we’re just looking at some properties of timestamp formats that are useful for CouchDB.

To make up for a good timestamp format, we need conventions. In the first example, we have a bunch of them: 12 months with specific names make up a year, we count years starting in the Common Era at 0 CE, so 2020 has meaning for us. In the second case, we just start counting seconds since January 1st. 1970. It doesn’t really matter what your conventions are, you just have to apply them consistently everywhere you use timestamps.

The seconds since format has a really nice property, because it is a relatively monotonically incrementing integer, which gives us a nice property when programming: we can compare two dates by their number of seconds and immediately see which one is the earlier and which one is the later date.

Unfortunately, humans can’t really work well with converting large numbers into the more human conventions of the other format we’ve shown above.

Enter ISO8601, a date format that is both easy to read for humans and easily comparable for computers. It looks like this: 2020-06-01T13:25:23Z. It gives us, in descending order, the most significant parts of a date: year, month, day, hour, minute, seconds, and a timezone identifier. If you need less precision, e.g. maybe you don’t need minutes and seconds, you can leave stuff off on the right end.

In CouchDB, you can store these dates as a string:

{
    "name": "Martin Luther King",
    "birthday: "1920-01-15"
}

If you prefer a timestamp format that is a little more concise, you can store the UNIX Epoch aka “seconds since midnight, 1 January 1970” as a number:

{
    "description":"wrote this article",
    "date": 1591014378
}