5

I am storing a document within a collection in a Cloud Firestore database. In this document, I want a reference to when the document was stored so I am using Firestore's FieldValue object which has a serverTimeStamp() function.

I am unable to parse this FieldValue object on the client as either a Date/NSDate or String. I have spent some time reading the Firestore iOS documentation and cannot find any leads on this.

There is no issue getting the FieldValue from the database to the client, however, I am unable to cast/convert the timeStamp of type FieldValue to anything.

Attempts to convert to string and date:

let timeStampString : String = message.timeStamp

let timeStampDate = Date(timeIntervalSince1970: message.timeStamp)

  • Cannot assign value of type FieldValue to type String
  • Cannot convert value of type FieldValue to expected argument type TimeInterval (aka Double)

Edit: After reviewing Doug Stevenson's answer, the best way to handle this is by casting your timeStamp value to a TimeStamp (not FieldValue) when reading the info on the client.

let timeStamp = document["yourTimeStampKey"] as! TimeStamp

rather than

let timeStamp = document["yourTimeStampKey"] as! FieldValue
Eli Whittle
  • 1,084
  • 1
  • 15
  • 19

1 Answers1

9

There's no parsing needed. Firestore timestamp fields are of type Timestamp, which you should use directly. It represents a point in time with nanosecond precision.

Code:

let timeStamp = document["yourTimeStampKey"] as! TimeStamp

rather than

let timeStamp = document["yourTimeStampKey"] as! FieldValue
Eli Whittle
  • 1,084
  • 1
  • 15
  • 19
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • I don't understand. When the value is retrieved on the client, I am storing the timestamp as a FieldValue by doing something like document["timeStamp"] as? FieldValue. How do you get from FieldValue to TimeStamp? Are you suggesting casting document["timeStamp"] as a TimeStamp and not as a FieldValue? – Eli Whittle Jun 16 '18 at 19:30
  • You shouldn't be getting anything of type FieldValue from a query. There are only two FieldValue type values, and they are used when you write data. You can't put a serverTimestamp() sentinel into a document, then get it right back out as a Timestamp. The timestamp gets calculated on the server when the document write occurs. – Doug Stevenson Jun 16 '18 at 19:47
  • I keep getting null value when trying to retrieve timestamp from firestore any ideas why? – Chris Aug 15 '19 at 02:09
  • Swift 5 `TimeStamp` -> `Timestamp` – Taras Nov 13 '20 at 20:27
  • Please check Answer: https://stackoverflow.com/a/56662889/2781088 – Mohit Kumar May 12 '21 at 14:49