转换后NSDate的日期为空

时间:2014-07-23 21:08:17

标签: ios nsdateformatter

我需要将String转换为日期,然后在UILabel中预设它。当我这样做时,我得到空字符串,UILabel也是null。这段代码有什么问题?

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"MMMM dd, YYYY HH:mm:ss"];

 NSDate *dateFromString;
 dateFromString = [dateFormat dateFromString:[tmpDevice valueForKey:@"date"]]; //This string is from array of object and is not null

     NSString *stringFromDate  = [dateFormat stringFromDate:dateFromString];

     NSLog(@"%@", stringFromDate); // here is null

     [cell.dateOfAddedCell setText: stringFromDate]; // and here also is null

2 个答案:

答案 0 :(得分:1)

根据您的评论,您有一个表示毫秒的字符串。您首先需要将该字符串转换为NSDate。然后,您可以将NSDate格式化为所需的字符串。

你忽略了为你的价值提及时代,但它似乎是基于1970年1月1日的标准。

NSString *millisString = tmpDevice[@"data"];
NSTimeInterval seconds = [miliisString doubleValue] / 1000;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM dd, yyyy HH:mm:ss"]; // notice is yyyy, not YYYY
NSString *stringFromDate = [dateFormat stringFromDate:date];
NSLog(@"%@", stringFromDate);

cell.dateOfAddedCell.text = stringFromDate;

答案 1 :(得分:1)

尝试替换此行:

dateFromString = [dateFormat dateFromString:[tmpDevice valueForKey:@“date”]];

有类似的东西:

dateFromString = [NSDate dateWithTimeIntervalSince1970:[(NSNumber *)[tmpDevice valueForKey:@“date”] intValue]];

您的代码无效,因为[tmpDevice valueForKey:@“date”]应该返回类似的内容:

@“2014年5月25日19:30:00”

但不是:

1406141698811

如果您想使用该方法:

dateFromString

希望它有意义