How to add a time interval to an NSDate?
Asked Answered
D

5

6

I have an NSDate and a duration. I need to get the time after the duration

Given:
The date is "2010-02-24 12:30:00 -1000"
duration is 3600 secs

I need to get "2010-02-24 13:30:00 -1000"

I thought dateWithTimeIntervalSinceReferenceDate:, would do the trick but I see now that this gives a date offset from 1 Jan 2001 GMT.

Is there another C function I need to use

Deception answered 24/2, 2010 at 20:33 Comment(0)
B
32

As DyingCactus states, you can use the addTimeInterval method of NSDate, but depending on the OS version is will create a compiler warning, since it is deprecated in 10.6 as of 2009-08-17.

The current recommended method is to use dateByAddingTimeInterval on NSDate:

NSDate *newDate = [oldDate dateByAddingTimeInterval:3600];

Note that if you are targeting 10.5 or earlier, the original answer will work.

Bethanie answered 24/2, 2010 at 21:19 Comment(1)
Thanks to all who answered. I did not read the docs well enough on this one.Deception
P
4

You want the class method dateWithTimeInterval:sinceDate: which takes the starting date and the interval NSDate docs

Profit answered 24/2, 2010 at 20:41 Comment(4)
I cannot find dateWithTimeInterval:sinceDate, but now that you made me look again I do see initWithTimeInterval:sinceDate:. That did the trick. Thanks.Deception
dateWithTimeInterval:sinceDate is a class method, rather than an instance method, that returns the result as an autoreleased NSDate. You get used to the naming conventions eventually.Toombs
OK, I see why I don't see dateWithTimeIntervalSinceDate. Your link is to the Mac OSX Reference Library. It is not available for the iPhone. But as others have pointed out there are several other ways to do it that are available on the iPhone.Deception
With your tags mentioning Cocoa instead of Cocoa-touch, and there being nothing about iPhone, it's not surprising that the answers you get are based on the Desktop SDK. I've corrected the tags for you.Toombs
B
3

You can use the addTimeInterval instance method of NSDate:

NSDate *newDate = [oldDate addTimeInterval:3600];

Edit: As Chip Coons correctly points out, this method has been deprecated. Please use one of the other methods instead.

Bet answered 24/2, 2010 at 21:2 Comment(0)
M
1

For those looking for a Swift 3.x version:

let newDate = Date.init(timeInterval: 2600, since: oldDate)
Misreckon answered 23/11, 2016 at 18:1 Comment(0)
C
0

Instead of using the deprecated addTimeInterval method, you can use the newer dateByAddingTimeInterval instance method of NSDate.

NSDate *newDate = [oldDate dateByAddingTimeInterval:2500];
Congeneric answered 15/7, 2014 at 21:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.