2010-10-10 38 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