Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Firebase Firestore Timestamp to Date (Swift)?

I have a date saved in a Firestore field as a timestamp that I want to convert to a Date in Swift:

June 19,2018 at 7:20:21 PM UTC-4

I tried the following but I get an error:

let date = Date(timeIntervalSince1970: postTimestamp as! TimeInterval)

Error:

Could not cast value of type 'FIRTimestamp' (0x104fa8b98) to 'NSNumber'

The reason why I want to convert to Date is so that I can use this Date extension to mimic timestamps you see on Instagram posts:

extension Date {
    func timeAgoDisplay() -> String {
        let secondsAgo = Int(Date().timeIntervalSince(self))

        let minute = 60
        let hour = 60 * minute
        let day = 24 * hour
        let week = 7 * day

        if secondsAgo < minute {
            return "\(secondsAgo) seconds ago"
        } else if secondsAgo < hour {
            return "\(secondsAgo / minute) minutes ago"
        } else if secondsAgo < day {
            return "\(secondsAgo / hour) hours ago"
        } else if secondsAgo < week {
            return "\(secondsAgo / day) days ago"
        }

        return "\(secondsAgo / week) weeks ago"
    }
}
like image 784
winston Avatar asked Jun 30 '18 15:06

winston


People also ask

How do I change firestore timestamp to date?

To convert a Firestore date or timestamp to a JavaScript Date, we use firebase. firestore. Timestamp. fromDate to convert the a date to a Firestore timestamp.

How do I convert a firestore date timestamp to a JS Date ()?

To convert a Firestore Timestamp into a Javascript date, just call . toDate() on the Timestamp.

How do you change firestore timestamp to date in flutter?

Method to convert it back to Datetime after fetching timestamp from Firestore: Firestore's timestamp contains a method called toDate() which can be converted to String and then that String can be passed to DateTime's parse method to convert back to DateTime.

What is the format of firestore timestamp?

Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.


1 Answers

Either do:

let date = postTimestamp.dateValue()

or you could do:

let date = Date(timeIntervalSince1970: postTimestamp.seconds)

See the Timestamp reference documentation.

like image 50
rmaddy Avatar answered Oct 12 '22 17:10

rmaddy