0

I am trying to update a UILabel with a firebase timestamp. I know that the timestamp will first need converting and formatting but I don't know the right method to use to do it all.

So, in my NewsFeedVC, I have the following:

  DataService.ds.REF_POSTS.queryOrdered(byChild: "postedDate").observe(.value) { (snapshot) in
        self.posts = []
        if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
            for snap in snapshot {
                if let postDict = snap.value as? Dictionary<String, AnyObject> {
                    let id = snap.key
                    let post = Post(postId: id, postData: postDict)
                    self.posts.append(post)
                }
            }
        }
        self.tableView.reloadData()
    }

What code do I need to implement to get the timestamp, convert it, format it (dd-mm-yy) and pass it to my NewsFeedCell so I can update the UILabel?

Thanks,

Scott

scottc00
  • 283
  • 1
  • 2
  • 8
  • I can't answer the firebase question, but I can help with the datformatting. You can create a DateFormatter and set its dateFormat to "dd-MM-yy". Then you can use it on the date from firebase to get the formatted date. – JillevdW Mar 09 '18 at 16:12
  • To convert the timestamp to an `NSDate` you'll need something like: `println(NSDate(timeIntervalSince1970: t/1000))`. See Kat's answer here: https://stackoverflow.com/questions/29243060/trying-to-convert-firebase-timestamp-to-nsdate-in-swift – Frank van Puffelen Mar 09 '18 at 18:19

1 Answers1

0

I implemented the following function to solve the problem:

func convertTimeStamp(serverTimestamp: Double) -> String {
    let x = serverTimestamp / 1000
    let date = Date(timeIntervalSince1970: x)
    let formatter = DateFormatter()
    formatter.dateFormat = "dd/MM/yy"

    return formatter.string(from: date as Date)
}
scottc00
  • 283
  • 1
  • 2
  • 8