0

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.

m0rtimer
  • 2,023
  • 1
  • 25
  • 31

1 Answers1

3

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.

  • Great -- yeah, I am in a non-eng speaking locale (JAPAN). How can I force the locale to fix the failure? (NSDate returns null) – m0rtimer Oct 10 '10 at 14:59