Swift convert NSTimeInteval to NSDate

This code is really confused.

A time interval is not a date. A date is a point in time. A time interval is the difference in seconds between two points in time. Whenever you have a time interval, you have the question "it is the number of seconds between what two dates? You correctly realise that adding a time interval stored in a database to NSDate () is unlikely to give a useful result, because the same call executed 10 seconds later will give a different date.

The date of a post should most likely be stored as an NSDate object. Core Data handles NSDate objects just fine. If you want to store time intervals, the date of the post must be converted to a time interval since some fixed reference date; you do that for example using "timeIntervalSinceReferenceDate". If you do that, I very strongly recommend that you don't call the variable "date" but something like "secondsSinceReferenceDate" which makes it obvious what to store when you are given a date, and how to convert that number back to an NSDate.

(The reason to call it "secondsSinceReferenceDate" is because there is plenty of code that tries to store milliseconds, or nanoseconds, and there is plenty of code that stores intervals since the epoch (Jan 1st 1970), so it's really good if someone reading your code knows immediately what the numbers mean by just looking at the variable name).


There is a initializer of NSDate that takes NSTimeInterval:

init(timeIntervalSinceReferenceDate ti: NSTimeInterval)

So just do:

var date = NSDate(timeIntervalSinceReferenceDate: 123)