Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse Firestore FieldValue to Date in Swift

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
like image 772
Eli Whittle Avatar asked Jun 16 '18 18:06

Eli Whittle


1 Answers

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
like image 113
Doug Stevenson Avatar answered Oct 18 '22 16:10

Doug Stevenson