How to parse Firestore FieldValue to Date in Swift
There's no parsing needed. Firestore timestamp fields are of type Timestamp, which you should use directly. It represents a point in time with nanosecond precision.
Code:
let timeStamp = document["yourTimeStampKey"] as! TimeStamp
rather than
let timeStamp = document["yourTimeStampKey"] as! FieldValue
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.
How to use FieldValue.serverTimestamp() as Model class in iOS - swift
Try this: assume we have a Firestore structure of this (as shown in the Firestore console)
timestamps
stamp_0
stamp: September 18, 2018 at 8:00:00 AM UTC-4
stamp_1
stamp: September 18, 2018 at 8:01:00 AM UTC-4
stamp_2
stamp: September 18, 2018 at 8:02:00 AM UTC-4
and we want to read the timestamps and print the key and the formatted timestamp to console.
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)
}
}
}
}
and the output is
stamp_0 2018-09-18 08:00:00 -0400
stamp_1 2018-09-18 08:01:00 -0400
stamp_2 2018-09-18 08:02:00 -0400
That's how you get to the timestamp data.
Storing it in your model class could be done in a number of ways depending on what you want to do with it: it could be stored as a formatted timestamp string (as shown in my answer), or a Firestore Timestamp object or a Date (NSDate) object. Just depends on your use case.
Timestamp API
Firestore FieldValue.serverTimestamp() is saving the local timestamp instead of server's timestamp
As you will read in the doc:
A Timestamp represents a point in time independent of any time zone or
calendar, represented as seconds and fractions of seconds at
nanosecond resolution in UTC Epoch time.
If you see, in the Firebase console, that "the local time is displayed in the document" it is because the Firebase console uses the timezone configuration of your computer to display the Timestamp value in your local time.
In conclusion:
- Question: "How do I store a single global time?" Answer: "With
FieldValue.serverTimestamp()
, it is already the case, it is stored in UTC". - It's up to you, in your app, to decide how to display the Timestamp values (as UTC or converted to the users' timezone).
How to extract local time from Firestore server timestamp?
Turns out I don't have to use secondsFromGMT. Use Timestamp.dateValue().timeintervalSince1970 and simply use a dateformatter on this to get the required time
let serverGMTTime = getServerTime() as? Timestamp
let convertedTime = Int(serverTime.dateValue().timeintervalSince1970)
let localDate = Date(timeintervalSince1970: TimeInterval(integerLiteral: convertedTime)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm"
let stringLocalTime = dateFormatter.string(from: localDate)
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 decrease a value using FieldValue in Firestore (SWIFT)?
There is no need for a decrement function, simply pass a negative value to the actual increment()
function:
document("fitness_teams/Team_1").
updateData(["step_counter" : FieldValue.increment(-500)])
And the value of your step_counter
field will be decremented by 500.
Flutter Cloud Firestore convert serverTimestamp to String
When you read a timestamp from a document in Cloud Firestore you get back a Timestamp
object.
To convert this to a regular date object, you can call the toDate()
method on it.
And then you can format that Date
object in any way you'd usually do, e.g. with the DateFormat
class as shown in Date Time format in Flutter dd/MM/YYYY hh:mm
Related Topics
Swift Nsusernotification Doesn't Show While App Is Active
Scrolling Delegate in Tableview
Why Upload Alamofire Background Request Don't Executes in Background
Skaction.Movebyx Not Setting Physicsbody.Velocity
Changing Texteditor Background Color in Swiftui for MACos
How to Draw Dashed Line in Arkit (Scenekit) Like in the Measure App
Differencebetween Date.Addingtimeinterval(_:) and Date.Advanced(By:)
Dynamic Datasource/Delegates for Uitableview in Swift
Error with Parse Query Findobjectsinbackgroundwithblock
Why Mark Something Final in Swift Except for Architectural Considerations
Value of Type 'Tags' Has No Member 'Lastused'
Remove \\U{E2} Characters from String
Crop/Mask Circular Image Node in Sprite Kit Gives Jagged Edges