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:


func getOrderDates() {

        let uid = Auth.auth().currentUser!.uid
        let orderDateHistoryRef = Database.database().reference().child("users/\(uid)/Orders/")
       
        orderDateHistoryRef.observeSingleEvent(of: .value, with: { (snapshot) in
      
            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

Accepted Reply

Seems you are very near to what you want.


As the error message is clearly showing, your updated line 17. is a code to convert a single `Date` to `String`.

Not to convert `[Date]`.


You can use `map` as in your line 11.

        let readableDates = dates.map {formatter.string(from: $0)}
        self.orderDateHistoryArray = readableDates

Replies

If your line 10. shows compile-time error as Error: "Binary operator '/' cannot be applied to operands of type 'String' and 'Int'",

then your line 11. `print(orderDate)` would never be executed so prints correctly does not make sense.


How have you get the output? Please show actual code you get this.

["-LQYspEghK3KE27MlFNE": 1541421618601,

“-LQsYbhf-vl-NnRLTHhK”: 1541768379422,

“-LQYDWAKlzTrlTtO1Qiz”: 1541410526186,

“-LQsILjpNqKwLl9XBcQm”: 1541764115618]


And if it repesents something taken from `value?["Date"]`, the type would be `[String: Int]`, not `[Int: String]`.

In

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'"


orderDate.values are String

Hence $0 is String as well


What are those Strings exactly ?


You should either:

- change the type of values in orderDate

- change $0 into Int($0)

I´m sorry for being unclear. The print statement is printong correctly when line 10 is commented out. And you where right. There was a typo error when you said: " And if it repesents something taken from `value?["Date"]`, the type would be `[String: Int]`, not `[Int: String]`."


So, I have made progress. Now the dates prints:

2018-11-09 11:48:35 +0000,

2018-11-05 09:35:26 +0000,

2018-11-09 12:59:39 +0000,

2018-11-05 12:40:18 +0000


This is correct with the current setup i guess, but I would like to have another format on the timeStamp.

Ideally: DD.MM.YY.


This is my best attempt so far:

(the error on line 17 is: "Cannot convert value of type '[Date]' to expected argument type 'Date'"

var orderDateHistoryArray = [Any]()


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       
        let cell = tableView.dequeueReusableCell(withIdentifier: "OrderHistoryCell") as! OrderHistoryTableViewCell
       
        cell.orderHistoryDateLabel.text = "\(orderDateHistoryArray[indexPath.row])"
       
        return cell
  }    



func getOrderDates() {

        let uid = Auth.auth().currentUser!.uid
        let orderDateHistoryRef = Database.database().reference().child("users/\(uid)/Orders/")
       
        orderDateHistoryRef.observeSingleEvent(of: .value, with: { (snapshot) in
      
            let value = snapshot.value as? NSDictionary
            if  let orderDate = value?["Date"] as? [String:Int] {
             
                let dates = orderDate.values.map {Date(timeIntervalSince1970: TimeInterval ($0/1000)) }
                let formatter = DateFormatter()
                formatter.calendar = Calendar(identifier: .iso8601)
                formatter.locale = Locale(identifier: "en_US_POSIX")
                formatter.timeZone = TimeZone(secondsFromGMT: 0)
                formatter.dateFormat = "h:mma, MMMM d, yyyy"
                let readable = formatter.string(from: dates) //Error: Cannot convert value of type '[Date]' to expected argument type 'Date'
                self.orderDateHistoryArray = dates 
   
                print(dates)
            }
            self.tableView.reloadData()
            // ...
        }) { (error) in
            print(error.localizedDescription)
        }
    }
}

Seems you are very near to what you want.


As the error message is clearly showing, your updated line 17. is a code to convert a single `Date` to `String`.

Not to convert `[Date]`.


You can use `map` as in your line 11.

        let readableDates = dates.map {formatter.string(from: $0)}
        self.orderDateHistoryArray = readableDates