如何从日期字符串中获取秒数?

时间:2010-10-10 14:42:07

标签: iphone objective-c nsdate nsdateformatter

在objective-C中,我想确定从日期字符串开始经过的秒数,例如:“星期六,2010年10月9日06:14:50 +0000”

我该怎么做?我迷失在NSDateFormatter的错综复杂的描述中。

1 个答案:

答案 0 :(得分: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找到用于日期格式的字符。

相关问题