在Objective-C中,我想确定从日期字符串中经过的秒数,例如:“Sat,2010年10月9日06:14:50 +0000”如何从日期字符串中获取秒数?
我该如何做?我迷失在NSDateFormatter的复杂描述中。
在Objective-C中,我想确定从日期字符串中经过的秒数,例如:“Sat,2010年10月9日06:14:50 +0000”如何从日期字符串中获取秒数?
我该如何做?我迷失在NSDateFormatter的复杂描述中。
这个例子给出了自当前时间逝去秒:
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);
注意,如果电话的区域是不是讲英语,转化为日期将因为“星期六”和“十月”失败未必意味着另一种语言中的同一事物。您可以强制dateFormatter上的语言环境来避免这种情况。
要在日期格式中使用的字符可以找到here。
重复的问题http://stackoverflow.com/questions/741830/getting-the-time-elapsed-objective-c – 2010-10-10 14:56:14