例1、 從服務器段獲取到的字符串轉化為時間如:轉化1416882712000
//網絡請求獲取的數據
NSString *time = [NSStringstringWithFormat:@%@,[[dateListobjectAtIndex:indexPath.row]gradeDate]];
NSInteger num = [time integerValue]/1000;(重點)
NSDateFormatter *formatter = [[[NSDateFormatteralloc]init]autorelease];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@YYYY-MM-dd];
NSDate*confromTimesp = [NSDatedateWithTimeIntervalSince1970:num];NSString*confromTimespStr = [formatterstringFromDate:confromTimesp];
cell.DateContent.text = confromTimespStr;
轉化之後結果為:2014-11-25
例2、如何如何將一個字符串如“ 20110826134106”裝化為任意的日期時間格式,下面列舉兩種類型:
NSString*string = @20110826134106;
NSDateFormatter *inputFormatter= [[[NSDateFormatter alloc] init] autorelease];
[inputFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@en_US] autorelease]];
[inputFormatter setDateFormat:@yyyyMMddHHmmss];
NSDate*inputDate = [inputFormatter dateFromString:string];
NSLog(@date= %@, inputDate);
NSDateFormatter *outputFormatter= [[[NSDateFormatter alloc] init] autorelease];
[outputFormatter setLocale:[NSLocale currentLocale]];
[outputFormatter setDateFormat:@yyyy年MM月dd日 HH時mm分ss秒];
NSString *str= [outputFormatter stringFromDate:inputDate];
NSLog(@testDate:%@,str);
兩次打印的結果為:
date= 2011-08-26 05:41:06 +0000
testDate:2011年08月26日 13時41分06秒