iOS NSString和NSDate转换

来源:互联网 发布:交换机基于mac的acl 编辑:程序博客网 时间:2024/06/05 08:30

后台返回的时间字符串不是标准的时间而是计算机时间的时候,我们需要将它们转换为标准时间,再进行转换。


//字符串转为时间,时间格式自己定 
 NSString * time = @"1501776000";   //时间字符串 
 NSInteger num = [time integerValue];   //转为int型 
 NSDateFormatter * formatter = [[NSDateFormatter alloc] init];     //时间管理
 [formatter setDateStyle:NSDateFormatterMediumStyle];      //时间方式
 [formatter setTimeStyle:NSDateFormatterShortStyle]; 
 [formatter setDateFormat:@"YYYY-MM-dd"]; 
 NSDate * confromTime = [NSDate dateWithTimeIntervalSince1970:num];
 NSString * comfromTimeStr = [formatter stringFromDate:confromTime]; 
 NSLog(@"%@",comfromTimeStr);


时间字符串格式转换为标准时间

NSString *string = @"20160707094106"; NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init]; [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; [inputFormatter setDateFormat:@"yyyyMMddHHmmss"]; NSDate *inputDate = [inputFormatter dateFromString:string]; NSLog(@"date= %@", inputDate); NSDateFormatter *outputFormatter= [[NSDateFormatter alloc] init]; [outputFormatter setLocale:[NSLocale currentLocale]]; [outputFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"]; NSString *str= [outputFormatter stringFromDate:inputDate]; NSLog(@"testDate:%@",str);


原创粉丝点击