0

I am trying to save a duration in Firestore. For example, a user has been working on an exercise for 4 minutes and 44 seconds. What is the recommended data type for this information?

It would be nice if the Firestore increment operator would work on the used data type. I thought about using a Timestamp, but in the Firebase SDK, the increment method expects a number, and a Timestamp is not a number.

Alex Mamo
  • 112,184
  • 14
  • 139
  • 167

1 Answers1

3

What is the recommended way of saving durations in Firestore?

Because you are talking about a duration, the solution would be to store it as a number, in particular as an Integer, which is a supported data-type. In your example, 4 minutes and 44 seconds will be stored as:

284

And this is because 4*60 + 44 = 284.

If you want to get back the number of hours and minutes, simply reverse the above algorithm.

It would be nice if the Firestore increment operator would work on the used data type.

Firestore already provides such an option. If you want to add, for example, an hour to an existing duration, you can use:

FieldValue.increment(3600) // 60 * 60

If you want to decrement with an hour, simply use:

FieldValue.increment(-3600)

I thought about using a Timestamp

A timestamp is not a duration. Firestore timestamps contain time units as small as nanoseconds. So a Timestamp object contains, the year, month, day, hour, minutes, seconds, milliseconds and nanoseconds. This will not solve your problem in any way.

Ishmeet
  • 668
  • 6
  • 16
Alex Mamo
  • 112,184
  • 14
  • 139
  • 167
  • You might wanna fix your answer with FieldValue.increment(60* 60) since the duration is stored in seconds. So 1 hour would actually be 3600 seconds. – Ishmeet Feb 03 '22 at 17:51