Convert Firebase Firestore Timestamp to Date (Swift)?
Either do:
let date = postTimestamp.dateValue()
or you could do:
let date = Date(timeIntervalSince1970: postTimestamp.seconds)
See the Timestamp reference documentation.
Converting Firestore Timestamp to Date data type
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.
Trying to convert Firebase timestamp to NSDate in Swift
ServerValue.timestamp()
works a little differently than setting normal data in Firebase. It does not actually provide a timestamp. Instead, it provides a value which tells the Firebase server to fill in that node with the time. By using this, your app's timestamps will all come from one source, Firebase, instead of whatever the user's device happens to say.
When you get the value back (from a observer), you'll get the time as milliseconds since the epoch. You'll need to convert it to seconds to create an NSDate. Here's a snippet of code:
let ref = Firebase(url: "<FIREBASE HERE>")
// Tell the server to set the current timestamp at this location.
ref.setValue(ServerValue.timestamp())
// Read the value at the given location. It will now have the time.
ref.observeEventType(.Value, withBlock: {
snap in
if let t = snap.value as? NSTimeInterval {
// Cast the value to an NSTimeInterval
// and divide by 1000 to get seconds.
println(NSDate(timeIntervalSince1970: t/1000))
}
})
You may find that you get two events raised with very close timestamps. This is because the SDK will take a best "guess" at the timestamp before it hears back from Firebase. Once it hears the actual value from Firebase, it will raise the Value event again.
How to decode a TimeStamp from the firebase Firestore in swift
It's a little unclear what the code in the question is doing but maybe if we just simplify the process, it will help.
Here's a function to write a Firestore Timestamp to a 'timestamp' collection, each document will have a unique documentID and a child field of 'stamp'
func writeTimestampAction() {
let now = Date()
let stamp = Timestamp(date: now)
let docRef = self.db.collection("timestamps").document()
docRef.setData( [
"stamp": stamp
])
}
and then a function to read all of the the timestamps from that collection and output them to the console in a yyyy-mm-dd format.
func readTimestampAction() {
self.db.collection("timestamps").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
if let stamp = document.get("stamp") {
let title = document.documentID
let ts = stamp as! Timestamp
let aDate = ts.dateValue()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
let formattedTimeZoneStr = formatter.string(from: aDate)
print(title, formattedTimeZoneStr)
}
}
}
}
}
Edit
He's an activity class that could be passed the Firestore snapshot
class ActivityClass {
var activity_name = ""
var activity_date: Timestamp?
convenience init(withDoc: QueryDocumentSnapshot) {
self.init()
if let stamp = withDoc.get("stamp") {
self.activity_date = stamp as? Timestamp
}
}
}
and when you're retrieving the data from Firestore just do this
for document in querySnapshot!.documents {
let myActivity = ActivityClass(withDoc: document)
//do something with myActivity
How do I convert timestamp value retrieved from Firestore to Date()?
dateValue()
already returns a Date
object. 2020-04-15 12:23:10 +0000
is just the String
representation of that Date
in your local timezone.
Convert a Date in Xcode to timestamp before adding to firestore
It looks like the Swift Firebase library has a class Timestamp
with an initializer that takes a Date
:
convenience init(date: Date)
And has a function that will convert a Timestamp
to a Date
:
func dateValue() -> Date
You could also calculate seconds and nanoseconds from a Date manually. That might look something like this:
extension Date {
var secondsAndNanoseconds: (seconds: Int, nanoseconds: Int) {
let result = timeIntervalSince1970
let seconds = Int(result)
return (seconds, Int(1000000000 * (result-Double(seconds))))
}
}
Related Topics
Swift Optional Inout Parameters and Nil
Retrieving Image from Firebase Storage Using Swift
How to Get Line Number and Function Name in Swift Language
Array Element Cannot Be Bridged to Objective-C
Get Description of Emoji Character
Saving Webview to Pdf Returns Blank Image
Nsdateformatter Return Wrong Date + Swift
How to Convert Hex Number to Bin in Swift
Swift - How to Mutate a Struct Object When Iterating Over It
Command Compileswiftsources Failed With a Nonzero Exit Code Xcode 10
Multiple Workers in Swift Command Line Tool
Retrieve Only 5 Users At a Time :Firebase [Like Instagram]
Get the Top Viewcontroller in iOS Swift
Swiftui. How to Change the Placeholder Color of the Textfield
How to Scale Text to Fit Parent View with Swiftui
Swiftui Create Image Slider with Dots as Indicators
How to Call a Function When a Swiftui Picker Selection Changes