user2401451
user2401451

Reputation: 21

How do you get the seconds since a past date to now?

How can I get the seconds that have passed since 1980-01-01 00:00:00 +1100 using NSTimeInterval?

// I need the function to use something like and am having an issue 

NSDate *aDate = (NSDate*)@"1980-01-01 00:00:00 +1100";
NSDate *seconds = [NSDate dateWithTimeInterval:60*60*24 sinceDate:aDate];
NSLog(@"seconds since Jan 1980 %@",seconds);

// I am trying to replace the following
//NSTimeInterval dateinterval = [[NSDate date] timeIntervalSince1970];

NSTimeInterval dateinterval = seconds;

NSDate only retrieves the GMT at +0000 which is not helpful in real world applications. Local dates are mandatory.

Is this too hard or can it not be done this way?

Upvotes: 0

Views: 326

Answers (1)

JAL
JAL

Reputation: 42489

You are initializing your NSDate object wrong. You can't directly cast an NSString as an NSDate, you need to use NSDateFormatter:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss z";

NSDate *aDate = [formatter dateFromString:@"1980-01-01 00:00:00 +1100"];
NSDate *now = [NSDate date];

NSTimeInterval seconds = [now timeIntervalSinceDate:aDate];

To format the date for a different time zone, use a new NSDateFormatter and set its local and timeZone.

Upvotes: 1

Related Questions