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.
What is the recommended way of saving durations in Firestore?
Because you are talking about 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
In code it will be as simply as:
val db = Firebase.firestore
db.collection(collName).document(docId).update("field", FieldValue.increment(3600))
If you want to decrement with an hour, pass a negative value:
FieldValue.increment(-3600)
And in code:
db.collection(collName).document(docId).update("field", FieldValue.increment(-3600))
I thought about using a Timestamp
A timestamp is not 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.