UPDATE:正如@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ž ?如果是這樣,我們來看看每一步。
首先,您需要將visit.olcreatedat
字符串(存儲在strVisitDate
中)轉換爲實際的NSDate對象visitDate
。因此,爲了使這一步的工作,你需要接受visit.olcreatedat
格式NSDateFormatter:YYYY-MM-DD HH:MM:SSž。
然後,你要得到的visitDate
的NSDate轉換成你喜歡的格式,所以你需要另一個NSDateFormatter,格式爲EEEE,DD MMM YYYY HH:MM:SSž。
- (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;
}
也許如果你設置日期格式以匹配日期的格式,你會有更好的運氣。 – 2013-05-01 20:32:01
[如何解析日期字符串到iOS中的NSDate對象?](http://stackoverflow.com/questions/4999396/how-to-parse-a-date-string-into-an-nsdate- object-in-ios) – 2013-05-01 20:33:30
'visit.olcreatedat'類型是什麼?它是一個'NSString'嗎?如果是這樣,請刪除對'stringWithFormat:'的調用。 – rmaddy 2013-05-01 20:41:15