add NSTimeInterval to NSDate in cocoa

l Beursgens picture l Beursgens · Apr 23, 2009 · Viewed 25.9k times · Source

I've got a NSDate that represents a specific time. The format of that date is hhmmss. I want to add an NSInterval value (specified in seconds) to that time value.

Example:

NSDate =         123000
NSTimeInterval = 3600

Added together = 133000

What is the best way to do this?

Answer

Stephen Darlington picture Stephen Darlington · Apr 23, 2009

Have you seen the Dates and Times Programming Topics for Cocoa manual?

Basically you need to convert your time into an NSDate. To convert a string to a date you use the NSDateFormatter class or maybe NSDateComponents if you already know the hours, minutes and seconds.

Your NSTimeInterval is just a double (i.e., 3600.0).

Then you use the dateByAddingTimeInterval method of NSDate to add the number of seconds to the time.

NSDate* newDate = [oldDate dateByAddingTimeInterval:3600.0];

You can then use either NSDateFormatter or NSDateComponents to get the new time back out again.