Mr Jax
Mr Jax

Reputation: 1017

Storing time only in Firestore

Is there a way to store a time value only in Firestore (without date)? I am trying to achieve the following in a Flutter app (business hours):

company [document]
  hours [map]
    - mon [map]
      - open: 08:00 [timestamp...?]
      - close: 18:00
    - tue [map]
      - open: 08:00
      - close: 18:00

I'd like to store it in a format that can be used in calculations (ie, how long until company closes today).

I've tried using TimeStamp and setting a generic date for each day (01/01/2001), and then only retrieving the time using DateFormat('HH:ss'), but the problem is that it then returns a string which can't be used in calculations.

Could anyone please point me in the right direction?

Upvotes: 4

Views: 3412

Answers (2)

Gaurav Ramanan
Gaurav Ramanan

Reputation: 3633

The Answer given by @Doug Stevenson is probably the most popular one out there. Especially because the time is readable in the Firestore console. Regarding your comment @Mr Jax Before doing any Time Calculations like 2:00 pm - 1:50 pm , we would need to convert both into Dates or DayJS / Moment Data structures and use the respective libraries.

A different (and probably amore robust approach) would be to use ms since midnight and store it in Firestore as an integer (Both approaches will take 8 bytes).

But this way there's no need for validation, and is somewhat standardized (since duration is usually stored as ms) at the cost of readability in the Firestore Console. You also wouldn't need to upgrade later if you need second or millisecond precision.

Both approaches are indexable and sortable from Firestore Queries since the integer comparison operations would be valid time comparison operations as well.

This can easily calculated, from Dan:

var d = new Date(),
    msSinceMidnight = d - d.setHours(0,0,0,0);

Conversion functions for your use case:

function timeToMsSinceMidnight(time) {
    const [hours, minutes] = time.split(':').map(Number);
    return (hours * 60 * 60 + minutes * 60) * 1000;
}

function msSinceMidnightToTime(ms) {
    const hours = Math.floor(ms / (60 * 60 * 1000));
    const minutes = Math.floor((ms % (60 * 60 * 1000)) / (60 * 1000));
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
}

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317487

Firestore doesn't provide a native "time of day" type. Timestamp is supposed to be used for a specific point in time, which wouldn't apply here.

A common way to represent time of day would be hours and minutes as a four digit integer in "mmss" format. So, for example, 1330 for 1:30pm. Or if you need seconds granularity, just add those to the end: 133000. You can then sort by these numbers to filter by time of day in addition to date. (You might want to store date in "YYYYMMDD" format.)

Upvotes: 13

Related Questions