As mentioned last time in my post Date — Class Reference, now we go a bit more in depth with DateComponents. In my opinion, this is the real powerhouse for dealing with time in Swift or Objective-C. When I was first learning iOS, I looked, understandably, at Date to work with dates. As such, a test project used Date and it’s initializers, including NSTimeInterval. When I had mentioned that at my local NSCoderNight, I was told to look into DateComponents, and boy was that good advice! Not only is it a pain to calculate the seconds for the intervals you want, what about dealing with Daylight Savings Time, leap years, or just plain different calendars! Now with DateComponents, I can set a date in a way that I understand, and in concert with Date and Calendar, it will even deal appropriately with the intricacies of calendars without me having to do so myself.
DateComponents can be used to either specify a specific date, or to specify a timespan in your Swift iOS apps. There is no difference between the uses as far as DateComponents is concerned you just set the appropriate components (year, day, hour, second, etc).
[Read more…]