iOS中日期和字符串的相互转化

例1、 从服务器段获取到的字符串转化为时间如:转化1416882712000



NSString *time =1416882712000;//服务器上的时间字符串

NSInteger num = [time integerValue]/1000;(重点)

NSDateFormatter *formatter = [[[NSDateFormatter alloc]init]autorelease];

[formatter setDateStyle:NSDateFormatterMediumStyle];

[formatter setTimeStyle:NSDateFormatterShortStyle];

[formatter setDateFormat:@YYYY-MM-dd];

NSDate*confromTimesp = [NSDate dateWithTimeIntervalSince1970:num];

NSString*confromTimespStr = [formatter stringFromDate: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秒

 

你可能感兴趣的:(iOS中日期和字符串的相互转化)