【问题标题】:Convert UNIX timestamp into Data - iOS将 UNIX 时间戳转换为数据 - iOS
【发布时间】:2013-10-16 15:43:21
【问题描述】:

我有一个 iOS 应用程序,它解析 JSON 数据源。在这个数据中是一些我存储在 NSString 中的 UNIX 时间戳。我想要做的是将这些时间戳转换为日期(月和日)。但我试图在不做任何划分的情况下做到这一点,因为根据我在网上阅读的内容,您应该始终使用 Apple 的 API 进行转换以获得准确的结果。

但是我的代码不工作,我得到这个错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 

这是我的代码:

NSString *time_string = [timestamps objectAtIndex:indexPath.row];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [formatter dateFromString:time_string];

cell.dateOfPub.text = [NSString stringWithFormat:@"%@", date];

我不明白我做错了什么。任何帮助将不胜感激。

谢谢,丹

【问题讨论】:

  • 你能告诉我们NSLog(@"%@", time_string)的结果吗?
  • @Kamaros 输出为:1359269613
  • 啊。是的,dateFromString 假设您传递的是像“2013-10-16”这样的字符串,而不是时间间隔。 Incmiko 得到了正确答案,尽管日期格式与您想要的不同。
  • 错误提示你的timestamps数组有NSNumber对象,而不是NSString对象。

标签: ios cocoa-touch date nsdate unix-timestamp


【解决方案1】:
double unixTimeStamp = [time_string doubleValue];
NSTimeInterval _interval=unixTimeStamp;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
[_formatter setLocale:[NSLocale currentLocale]];
[_formatter setDateFormat:@"dd.MM.yyyy"];
NSString *_date=[_formatter stringFromDate:date];

【讨论】:

  • 很高兴为您提供帮助 :)
  • 请记住,time_string 变量实际上是在引用 NSNumber 对象(基于错误消息)。这段代码之所以有效,是因为 NSStringNSNumber 都有一个 doubleValue 方法。
猜你喜欢
  • 2012-08-19
  • 2013-04-07
  • 1970-01-01
  • 2023-03-18
  • 2020-10-19
  • 2013-07-02
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多