Reputation: 731
I'm saving to my Firestore database a time stamp from my node js server, For some reason it save the Date() as string in the database.
I'm trying to load the documents in my IOS app but I could not find a way to convert the string saved by JS to swift all of the solutions I've tried produces the app to crash because of nil value after the convertion.
This is my code
func convertStringToDate(date:String) -> Date{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm'"
let returnValue = dateFormatter.date(from: date)
return returnValue!
}
date Value that I receive from Firestore is :
date String "Fri Aug 03 2018 22:43:00 GMT+0300 (IDT)"
Upvotes: 1
Views: 515
Reputation: 2076
You could just save the timestamp serverValue from Firestore. It gives you a TIMESTAMP in unix time, this is a number that you can convert in swift to human Time.
in your Node server
const timestamp = firebase.firestore.FieldValue.serverTimestamp()
ref.update({ updatedAt: timestamp })
in Swift
let date = Date(timeIntervalSince1970: YOUR_TIMESTAMP_HERE_AS_VAR)
Upvotes: 4
Reputation: 920
You can convert get your date like this :
var dateStr = "Fri Aug 03 2018 22:43:00 GMT+0300 (IDT)"
guard let ind = dateStr.index(of: "G") else {return}
dateStr = String(dateStr[..<ind].trimmingCharacters(in: CharacterSet.whitespaces))
print(convertStringToDate(date: dateStr))
func convertStringToDate(date:String) -> Date{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE MMM dd yyyy HH:mm:ss"
let returnValue = dateFormatter.date(from: date)
let timeZone = TimeZone.current
return returnValue!.addingTimeInterval(TimeInterval(timeZone.secondsFromGMT()))
}
Upvotes: 1