Converting Firestore Timestamp to Date data type

2019-06-08 14:12发布

Few days ago, I just updated my firebase pod to the latest version, and in my debugging area, I got message that said that I have to update from timestamp data type to Date (something like that, I forget actually).

and I also have to change the DB settings like below

let db = Firestore.firestore()
let settings = db.settings
settings.areTimestampsInSnapshotsEnabled = true
db.settings = settings

after add the code above, the error message in my debugging area in Xcode disappears.

As far as I remember, I also had to change the data type in my client from Timestamp to Date data type, I haven't changed this because the error message in my debugging area in Xcode have disappeared.

As a result, I get not correct Date in my app.

Could you please share again the conversion step from TimeStamp to Date ? because as far as I remember I had to do some steps to follow. I can't find it in the firebase documentation.

Thank you very much :)

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-08 14:30

This is the message from the debugger

The behavior for system Date objects stored in Firestore is going to change AND YOUR APP MAY BREAK. To hide this warning and ensure your app does not break, you need to add the following code to your app before calling any other Cloud Firestore methods:

let db = Firestore.firestore()
let settings = db.settings
settings.areTimestampsInSnapshotsEnabled = true
db.settings = settings

With this change, timestamps stored in Cloud Firestore will be read back as Firebase Timestamp objects instead of as system Date objects. So you will also need to update code expecting a Date to instead expect a Timestamp. For example:

// old:
let date: Date = documentSnapshot.get("created_at") as! Date
// new:
let timestamp: Timestamp = documentSnapshot.get("created_at") as! Timestamp
let date: Date = timestamp.dateValue()

Please audit all existing usages of Date when you enable the new behavior. In a future release, the behavior will be changed to the new behavior, so if you do not follow these steps, YOUR APP MAY BREAK.

查看更多
登录 后发表回答