0
votes

I have been searching for a while and haven't found a good answer for this. I currently have when a user posts a photo, it takes an nsdate(timeIntervalSince1970) and puts it as a value when uploaded to firebase. One problem, the current way I change the nsdate to a timeStamp or mins/hours/days since it was posted is not Turing out to good, it does not correct to when a day passes, it just shows what time it was posted at. I was hoping I could get an answer or referred to an algorithm that can change an nsdate(timeIntervalSince1970) to a timeStamp or string that just gives me how many hours ago it was posted, and every 24 hours, change it to 1 day(s). I apologize ahead of time for asking kinda of easy question, I'm guessing. Here is my current code:

    if let seconds = posts[visibli.row].timeStamp {
        let time = NSDate(timeIntervalSince1970: TimeInterval(seconds))
        let formatter = DateFormatter()
        formatter.dateFormat = "hh:mm a"
        labelTime.text = formatter.string(from: time as Date)
    }

Thank you for any Help!

2
FYI - Do not use NSDate. Just use Date. - rmaddy

2 Answers

1
votes

What you are looking for is DateComponentsFormatter. You can look at the different formatters Foundation offers, here.

If you want to have a string that denotes the amount of time that has elapsed since a given date, you can say something like:

if let seconds = posts[visibli.row].timeStamp {
    let time = Date(timeIntervalSince1970: TimeInterval(seconds))
    let dateComponentsFormater = DateComponentsFormatter()
    dateComponentsFormater.unitsStyle = .positional
    let string = dateComponentsFormater.string(from: time, to: Date())
    labelTime.text = string
}
0
votes

Current Timestamp as String.

 public class func getCurrentTimeStamp()->String{
        return String(describing: NSNumber(value: round(NSDate().timeIntervalSince1970 * 1000)))
    }

this function use get current timestamp.