Convert timestamp from Firebase to readable date

I would like to convert a timestamp posted in firebase to readable data. I am able to read the timestamp, but not able to convert it, or append it to an array.
This is my progress:

var orderDateHistoryArray = [String:Int]()`

    func getOrderDates() {
      
        let uid = Auth.auth().currentUser!.uid
        let orderDateHistoryRef = Database.database().reference().child("users/\(uid)/Orders/")
        
        orderDateHistoryRef.observeSingleEvent(of: .value, with: { (snapshot) in
       
            // Get user value
            let value = snapshot.value as? NSDictionary
            if  let orderDate = value?["Date"] as? [Int:String] {
               self.orderDateHistoryArray += Array(orderDate.values).map{ Date(timeIntervalSince1970: TimeInterval($0/1000))} // This fails. Error: "Binary operator '/' cannot be applied to operands of type 'String' and 'Int'"

                print(orderDate) 
            }
            self.tableView.reloadData()
            // ...
        }) { (error) in
            print(error.localizedDescription)
        }
    }

}

The print(orderDate) statement prints correctly:

[“-LQYspEghK3KE27MlFNE”: 1541421618601,
“-LQsYbhf-vl-NnRLTHhK”: 1541768379422,
“-LQYDWAKlzTrlTtO1Qiz”: 1541410526186,
“-LQsILjpNqKwLl9XBcQm”: 1541764115618]

This is childByAutoID : timeInMilliseconds

So, I want to read out the timeInMilliseconds , convert it to a readable timestamp and append it to the orderDateHistoryArray

Hi @stianand, not sure if this could directly help but maybe give you an idea of how to get the timestamp for your orders. Here is an extension for Date,

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
        
        let quotient: Int
        let unit: String
        
        if secondsAgo < minute {
            quotient = secondsAgo
            unit = "second"
        } else if secondsAgo < hour {
            quotient = secondsAgo / minute
            unit = "minute"
        } else if secondsAgo < day {
            quotient = secondsAgo / hour
            unit = "hour"
        } else if secondsAgo < week {
            quotient = secondsAgo / day
            unit = "day"
        } else {
            let df = DateFormatter()
            df.dateFormat = "MMMM d y"
            return df.string(from: self)
        }
        
        return "\(quotient) \(unit)\(quotient == 1 ? "" : "s") ago"
    }
}

Best,
Gina

Hi @stianand,
For converting long dates into human readable format you can use the DateFormatter however using the ISO format is a much better option than custom formats.

Especially in cases where you might want to use JSONCoding

cheers,

This topic was automatically closed after 166 days. New replies are no longer allowed.