Reputation: 303
NSDate *newDate=[newDate dateByAddingTimeInterval:difference];
Now I want to convert this newDate to NStimeInterval.
How can I do this conversion?
Upvotes: 2
Views: 15827
Reputation: 894
Just a bit shorter:
NSDate *date = ...
NSTimeInterval interval = [date timeIntervalSinceReferenceDate];
And to get it back:
date = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:timeInterval];
Upvotes: -1
Reputation: 952
NDDate
and NSTimeInterval
are two diferent things, you cannot convert a NSDate
to a NSTimeInterval
and vice-versa.
NSDate
represents an absolute date and NSTimeInterval
represents the time between two dates.
However you can create a NSTimeInterval from a reference date with this method:
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate
You can do it like this:
NSDate *referenceDate = /* Your reference date */
NSDate *date = /* Your date */
NSTimeInterval timeInterval = [date timeIntervalSinceDate:referenceDate];
Upvotes: 13
Reputation: 122391
As I have mentioned in the comments above, you need to know what you want the NSTimeInterval
to represent as it's the distance between two points in time (i.e. two NSDate
instances).
If you want it to represent the time between your newDate
and 01-Jan-2001 GMT you can use:
- (NSTimeInterval)timeIntervalSinceReferenceDate;
(reference).
However if you want it to represent the time since another reference date, you need to create that reference date as an NSDate
object and use:
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate;
(reference).
Upvotes: 2