Storing dates with angular and firebase

2020-05-06 12:45发布

问题:

I'm creating an angular + firebase food journal and I'm having a logic freeze concerning dates and how best to store them. My data structure looks like:

{
    "uid": {
        "profile": {
            "name": "name"
        },
        "journal": {
            "date1": {
                "breakfast": "",
                "lunch": "",
                "dinner": ""
            },
            "date2": {
                ...
            }
        }
    }
}

Obviously, I only want to set a 'date' value once and be able to set it and retrieve it from any timezone. I initialy set the 'date' key to a rounded off timestamp with hours, minutes, seconds all set to 0. But that didn't work b/c of the timezone issue.

I then decided to just use dateObject.toDateString() as the unique 'date' key. That worked fine until I realized that doing so would limit how I can query firebase.

I want to be able to query firebase for a range of days as well as maintain order. For example, say I want to view the entries for "Wed Jan 21 2015" to "Thu Jan 29 2015". Getting the data for those days would require a separate query and firebase request. Where as, if I stored a number, I could use firebase's range queries; startAt(), endAt(), and equalTo().

My current solution/thought is to store an 8 digit number made up of a date object's 4 digit year, 2 digit month and 2 digit day where "Wed Jan 21 2015" would be stored as 20150021 and "Thu Jan 29 2015" as 20150029. And then just parse the numbers client side to create local date objects.

But it seems like I'm either over-looking something or over-thinking something. Is there a better way to accomplish this?

回答1:

Storing dates in yyyyMMdd format is fairly common. It has the advantage that the resulting values are numerically comparable, i.e. the number for tomorrow is bigger than the one for today.

An even more common alternative is to store in "(milli)seconds since the epoch". Not only is that numerically comparable, but it is also what Date.now() returns and can be passed into new Date().