我需要帮助。,我有这个日期在这种格式的UIlabel 04/26/2013。我怎样才能重新格式化为04.26.2013?我已经有如下代码:重新格式化字符串
UILabel *timelabel = [[UILabel alloc] initWithFrame:CGRectMake(xx, xx, xx, xx)];
[timelabel setText:dateToday];
dateToday
值04/26/2013
。
我需要帮助。,我有这个日期在这种格式的UIlabel 04/26/2013。我怎样才能重新格式化为04.26.2013?我已经有如下代码:重新格式化字符串
UILabel *timelabel = [[UILabel alloc] initWithFrame:CGRectMake(xx, xx, xx, xx)];
[timelabel setText:dateToday];
dateToday
值04/26/2013
。
timelabel.text = [dateToday stringByReplacingOccurrencesOfString:@"/" withString:@"."];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM.dd.yyyy"];
NSString *stringFromDate = [formatter stringFromDate:[NSDate date]];
NSLog(@"today : %@", stringFromDate);
OP不问 “今天”。 – Raptor 2013-04-26 06:52:20
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM.dd.yyyy"];
NSDate *date = [dateFormatter dateFromString:dateToday];
if(date != nil) {
NSString *formattedDateString = [dateFormatter stringFromDate:date];
[timelabel setText:formattedDateString];
} else {
[timelabel setText:@"Invalid Date"];
}
添加错误检查。总是检查输入字符串是否是有效的日期字符串。
参考:Date Formatting Guide (though it is for Mac; iOS applies the same)
聪明!如果'dateToday'包含无效值呢? – Raptor 2013-04-26 06:51:55