首页 > 代码库 > iOS中日期和字符串的相互转化(特殊)
iOS中日期和字符串的相互转化(特殊)
例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秒
其他时间转化的网址收集:
http://longquan.iteye.com/blog/1873268
http://blog.csdn.net/l_ch_g/article/details/8217725
http://www.open-open.com/lib/view/open1374292431912.html
iOS中日期和字符串的相互转化(特殊)