2013-04-26 76 views
0

我需要幫助。,我有這個日期在這種格式的UIlabel 04/26/2013。我怎樣才能重新格式化爲04.26.2013?我已經有如下代碼:重新格式化字符串

UILabel *timelabel = [[UILabel alloc] initWithFrame:CGRectMake(xx, xx, xx, xx)]; 
[timelabel setText:dateToday]; 

dateToday04/26/2013

回答

1
timelabel.text = [dateToday stringByReplacingOccurrencesOfString:@"/" withString:@"."]; 
+0

聰明!如果'dateToday'包含無效值呢? – Raptor 2013-04-26 06:51:55

2
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"MM.dd.yyyy"]; 
NSString *stringFromDate = [formatter stringFromDate:[NSDate date]]; 
NSLog(@"today : %@", stringFromDate); 
+0

OP不問 「今天」。 – Raptor 2013-04-26 06:52:20

1
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)