I have a @State var tripDate = Date()
I want to add to firestore db
func addData(tripDate: Date) {
// Get a reference to the database
let db = Firestore.firestore()
// Add a document to a collection
db.collection("tripDate":tripDate]) { error in
// Check for errors
if error == nil {
// No errors
// Call get data to retrieve latest data
self.getData()
}
else {
// Handle the error
}
}
}
and also get data from firestore
func getData() {
// Get a reference to the database
let db = Firestore.firestore()
// Read the documents at a specific path
db.collection("Event").getDocuments { snapshot, error in
// Check for errors
if error == nil {
// No errors
if let snapshot = snapshot {
// Update the list property in the main thread
DispatchQueue.main.async {
// Get all the documents and create Todos
self.list = snapshot.documents.map { d in
// Create a Todo item for each document returned
return Event(id: d.documentID,
tripDate: d["tripDate"] as! Date,
)
}
}
}
}
else {
// Handle the error
}
}
}
this is the button to add
Button(action: {
Eventmodel.addData(tripDate: tripDate)
}) {
Text("Submit")
}
any idea how can I covert the date in these cases to timestamp (in these functions) since Firestore doesn’t take Date it rather takes timestamps and incase I remain putting it as a date, fatal error occurs and the app crashed and freezes , any idea thank you alot !
2
Answers
You can convert
Date
into a timestamp by using itstimeIntervalSince1970
property. If the API you’re using supports floating point numbers, you can use it as is, or just convert it to aString
. An alternative could be using aDateFormatter
.It looks like the Swift Firebase library has a class
Timestamp
with an initializer that takes aDate
:And has a function that will convert a
Timestamp
to aDate
:You could also calculate seconds and nanoseconds from a Date manually. That might look something like this: