views:

41

answers:

1

In objective-C, I want to determine the seconds elapsed from a date string such as: "Sat, 09 Oct 2010 06:14:50 +0000"

How do I do this? I got lost in the convoluted descriptions of NSDateFormatter.

+2  A: 

This example gives seconds elapsed since current time:

NSString *dateString = @"Sat, 09 Oct 2010 18:14:50 +0000";

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[df setLocale:usLocale];
[usLocale release];

NSDate *date = [df dateFromString:dateString];
[df release];

NSTimeInterval secondsSinceNow = [date timeIntervalSinceNow];

NSLog(@"date = %@", date);
NSLog(@"secondsSinceNow = %f", secondsSinceNow);

Note that if the phone's region is not English-speaking, the conversion to date will fail since "Sat" and "Oct" may not mean the same thing in another language. You can force a locale on the dateFormatter to avoid this.

Characters to use in date formatting can be found here.

aBitObvious
Great -- yeah, I am in a non-eng speaking locale (JAPAN). How can I force the locale to fix the failure? (NSDate returns null)
Eric
Added the setting of locale.
aBitObvious
thanks for this!
Eric