Tarvo Mäesepp Tarvo Mäesepp - 3 months ago 32
Swift Question

Wrong time since.. from timestamp

I added timestamp to Firebase database formatted like:


So I wanted to calculate the time since this timestamp was created however as an output I get something like this:
1969-12-31 23:32:04 +0000

It sees somehow correct but how I am able to convert it now to like 5 minutes ago, etc.

I am doing my calculations like this:

let timestamp = postsArray[indexPath.row].timestamp//query timestamp from Firebase
let date = NSDate(timeIntervalSince1970: timestamp! )//Readable date
let timeSincePost = (NSDate().timeIntervalSinceNow-NSDate().timeIntervalSince(date as Date))//Calculate time since
print("TimeSince", NSDate(timeIntervalSince1970: timeSincePost))

I went trough many similar questions in many languages but they are all so different. Am I doing it very wrong?


NSDate().timeIntervalSinceNow return value close to 0.

NSDate() — creates date with current timestamp, you can call it now. timeIntervalSinceNow here will be difference between time of creating data and method call, miniscule value.

So this:

NSDate().timeIntervalSinceNow-NSDate().timeIntervalSince(date as Date)

Can be seen like this:

0 - now.timeIntervalSince(date as Date)

For all dates in past now.timeIntervalSince(date as Date) is positive, and 0 - positive = negative

And in the end you're subtracting time interval from January 1st, 1970 and get your date of 1969. Btw, why are you doing this?

Also, stop using NSDate in Swift 3, just use Date.

And use this method for timeSincePost calculation.

how I am able to convert it now to like 5 minutes ago etc...

Just use DateFormatter with doesRelativeDateFormatting set to true and get stringFromDate with original date you got with Firebird timestamp.