Reputation:
How can I save a date
from swift with the current hour
from my app into the Firestore document?
let todayDateAndHour = Date()
This is the data I am trying to save to Firestore:
let data : [String: Any] = [
"DateAndHour" : todayDateAndHour
]
I send this data to CloudFunctions with this call:
Functions.functions().httpsCallable("saveDate").call(data) {
}
Then in Cloud Function I do the following:
exports.saveDate = functions.https.onCall((data, context) => {
const cloudDateAndHour = data.DateAndHour
return db.collection('MyCollection').doc('MyDocument').set({
timeStampDateAndHour: cloudDateAndHour
})
}
I know my cloud funcitons work but the date I believe I need to convert it to another format in swift so it can be saved in firestore? How would I do that?
Upvotes: 0
Views: 361
Reputation: 5523
Are you asking how to save the date as a String
? You can use DateFormatter
for that, and your implementation might look something like this:
let todayDateAndHour = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hhZ"
let dateString = dateFormatter.string(from: todayDateAndHour) //"2019-12-20 02-0800"
let data : [String: Any] = ["DateAndHour" : dateString]
That said, Firestore also supports Date
s, so this is really just based on your preference. Check their docs for details.
Later on if you wanted to turn these strings back into Date
s you can do so with the same formatter like so:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hhZ"
let fullDate: Date? = dateFormatter.date(from: dateString)
Please note that (as I indicated here) that DateFormatter.date(from: String)
return an Optional<Date>
for the obvious reason that you could pass any random String
into the method. You will also need to make sure that the DateFormatter.dateFormat
is the same going in as it is coming out.
Upvotes: 1