SWIFT converts NSTimeInteval to NSDate

I am following the Objective-C tutorial, and the mentor can apply the NSTimeInterval object to the NSDate object.

The lesson uses CoreData and saves the publication date as NSTimeInterval, later we want to get this interval and set it as a formatted date string, which will be presented as the section title in UITableVIewController.

class DiaryEntry: NSManagedObject { @NSManaged var date: NSTimeInterval @NSManaged var body: String @NSManaged var imageData: NSData @NSManaged var mood: Int16 @NSManaged var location: String func sectionName() -> String { let date = NSDate().dateByAddingTimeInterval(self.date) let f = NSDateFormatter() f.dateFormat = "MMM yyy" return f.stringFromDate(date) } } 

This is mainly about the line:

 let date:NSDate = NSDate().dateByAddingTimeInterval(self.date) 

What now actually adds the set date to the current date, and this is not the behavior that I want.

How to convert self.date variable to self.date object in SWIFT?

+8
ios swift nsdate core-data
source share
2 answers

There is an initializer of NSDate that accepts NSTimeInterval :

 init(timeIntervalSinceReferenceDate ti: NSTimeInterval) 

So simple:

 var date = NSDate(timeIntervalSinceReferenceDate: 123) 
+15
source share

This code is really confusing.

The time interval is not a date. Date is a point in time. The time interval is the difference in seconds between two time points. Whenever you have a time interval, the question arises: "Is this the number of seconds between two dates? Do you understand correctly that adding a time interval stored in the database in NSDate () is unlikely to give a useful result, since that a call made after 10 seconds will give a different date.

The publication date is likely to be stored as an NSDate. Core Data handles NSDate objects just fine. If you want to store time intervals, the message date must be converted to a time interval from some fixed key date; you do this, for example, using "timeIntervalSinceReferenceDate". If you do this, I strongly recommend that you not call the "date" variable, but something like "secondsSinceReferenceDate", which makes it obvious what to store when the date is given to you, and how to convert that number back to NSDate,

(The reason this is called "secondsSinceReferenceDate" is because there is a lot of code that tries to store milliseconds or nanoseconds, and there is a lot of code that stores intervals from the era (January 1, 1970), so it’s really good if someone reading your code will immediately know what the numbers mean by just looking at the variable name).

+2
source share

All Articles