我有以下代码在 UITableView 的 cellForRowAtIndexPath 中调用。
self.dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setDateFormat:@"EEEE, dd MMM yyyy HH:mm:ss z"];
OLVisit *visit = [self.visits objectAtIndex:indexPath.row];
NSString *strVisitDate = [NSString stringWithFormat:@"%@", visit.olcreatedat];
NSDate *visitDate = [self.dateFormatter dateFromString:strVisitDate];
strVisitDate = [self.dateFormatter stringFromDate:visitDate];
从 visit.olcreatedat 返回的字符串采用以下格式(如下面的调试器屏幕截图所示)“2013-04-09 11:55:25 +0000”。
我在 visitDate 中返回了一个 nil NSDate 值。
谁能帮我解决这个问题?
最佳答案
更新:正如@rmaddy 所指出的,对于visit.olcreatedat
是什么存在误解。
第一个答案是基于 visit.olcreatedat
是一个假设
NSDate。对于假定 visit.olcreatedat
是包含格式化日期的 NSString 的答案,请阅读此答案的第二部分。
visit.olcreatedat 是一个 NSDate
- (void)viewDidLoad {
[super viewDidLoad];
// Alloc the date formatter in a method that gets run only when the controller appears, and not during scroll operations or UI updates.
self.outputDateFormatter = [[NSDateFormatter alloc] init];
[self.outputDateFormatter setDateFormat:@"EEEE, dd MMM yyyy HH:mm:ss z"];
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath: {
// dequeue or create the cell...
// ...
// ...
OLVisit *visit = [self.visits objectAtIndex:indexPath.row];
NSString * strVisitDate = [self.outputDateFormatter stringFromDate:visit.olcreatedat];
// Here you can assign the string to the right UILabel
cell.textLabel.text = strVisitDate;
return cell;
}
visit.olcreatedat 是一个 NSString
是否要将 visit.olcreatedat
转换为 EEEE, dd MMM yyyy HH:mm:ss z 格式?如果是这样,让我们完成每个步骤。
首先,您需要将 visit.olcreatedat
字符串(存储在 strVisitDate
中)转换为实际的 NSDate 对象,visitDate
。因此,要使这一步有效,您需要一个接受 visit.olcreatedat
格式的 NSDateFormatter:yyyy-MM-dd HH:mm:ss z。
然后,你想把得到的visitDate
NSDate转换成你喜欢的格式,所以你需要另一个NSDateFormatter,格式是EEEE, dd MMM yyyy HH:mm:ss z.
- (void)viewDidLoad {
[super viewDidLoad];
// Alloc the date formatter in a method that gets run only when the controller appears, and not during scroll operations or UI updates.
self.inputDateFormatter = [[NSDateFormatter alloc] init];
[self.inputDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
self.outputDateFormatter = [[NSDateFormatter alloc] init];
[self.outputDateFormatter setDateFormat:@"EEEE, dd MMM yyyy HH:mm:ss z"];
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath: {
// dequeue or create the cell...
// ...
// ...
OLVisit *visit = [self.visits objectAtIndex:indexPath.row];
NSString *strVisitDate = visit.olcreatedat;
NSDate *visitDate = [self.inputDateFormatter dateFromString:strVisitDate];
strVisitDate = [self.outputDateFormatter stringFromDate:visitDate];
// Here you can assign the string to the right UILabel
cell.textLabel.text = strVisitDate;
return cell;
}
关于ios - NSDateFormatter 不格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16325893/