【问题标题】:How to get seconds elapsed from a Date String?如何从日期字符串中获取经过的秒数?
【发布时间】:2010-10-10 14:42:06
【问题描述】:

在 Objective-C 中,我想确定从日期字符串经过的秒数,例如:“Sat, 09 Oct 2010 06:14:50 +0000”

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

【问题讨论】:

标签: iphone objective-c nsdate nsdateformatter


【解决方案1】:

这个例子给出了自当前时间以来经过的秒数:

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);

请注意,如果手机所在地区不是说英语的,则转换为日期将失败,因为“Sat”和“Oct”在另一种语言中的含义可能不同。您可以在 dateFormatter 上强制使用语言环境来避免这种情况。

可以在here找到用于日期格式的字符。

【讨论】:

  • 太棒了——是的,我在非英语地区(日本)。如何强制语言环境修复失败? (NSDate 返回 null)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多