2010-10-10 58 views
0

在Objective-C中,我想确定从日期字符串中经过的秒数,例如:“Sat,2010年10月9日06:14:50 +0000”如何从日期字符串中获取秒数?

我该如何做?我迷失在NSDateFormatter的复杂描述中。

+0

重复的问题http://stackoverflow.com/questions/741830/getting-the-time-elapsed-objective-c – 2010-10-10 14:56:14

回答

3

这个例子给出了自当前时间逝去秒:

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

+0

伟大的 - 是的,我在一个非英语区域设置(日本)。我如何强制地区来修复失败? (NSDate返回null) – m0rtimer 2010-10-10 14:59:21

+0

添加区域设置。 – Anna 2010-10-10 15:03:54