ios-|ios- 常见数据类型转换

1、NSDate转NSString

+ (NSString *)stringFromDate:(NSDate *)date { //获取系统当前时间 NSDate *currentDate = [NSDate date]; //用于格式化NSDate对象 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //设置格式:zzz表示时区 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"]; //NSDate转NSString NSString *currentDateString = [dateFormatter stringFromDate:currentDate]; //输出currentDateString NSLog(@"%@",currentDateString); return currentDateString; }

2、NSString转NSDate
+ (NSDate *)dateFromString:(NSString *)string { //需要转换的字符串 NSString *dateString = @"2015-06-26 08:08:08"; //设置转换格式 NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ; [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //NSString转NSDate NSDate *date=[formatter dateFromString:dateString]; return date; }

3、字典转json格式字符串:
- (NSString*)dictionaryToJson:(NSDictionary *)dic { NSError *parseError = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError]; return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; }

4、json格式字符串转字典
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {if (jsonString == nil) {return nil; }NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *err; NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonDataoptions:NSJSONReadingMutableContainerserror:&err]; if(err) {NSLog(@"json解析失败:%@",err); return nil; }return dic; }

6、字符串NSString转NSNumber
NSString * str = @"890909"; // 字符串转为NSInteger类型 NSInteger num = [str integerValue]; NSLog(@"%li",num); // 字符串转为NSNumber对象类型 NSNumber * nums = @(num); NSLog(@"******%@",nums); NSString *str = @"120". NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; NSNumber *numTemp = [numberFormatter numberFromString:str]; 简化写法 NSNumber * nums = @([str integerValue]);

7、NSNumber转字符串NSString
NSString *string = [NSString stringWithFormat:@"%d",ivalue];

8、获取字符串中的数字
NSString *urlString = @"fafadfdas12.4fdfas45dfa"; //方法一 NSScanner *scanner = [NSScanner scannerWithString:urlString]; [scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil]; double number; [scanner scanDouble:&number]; NSString *num=[NSString stringWithFormat:@"%g",number]; //12.4//方法二 NSCharacterSet* nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet]; int remainSecond =[[urlString stringByTrimmingCharactersInSet:nonDigits] intValue]; NSLog(@" num %d ",remainSecond); //12

    推荐阅读