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
推荐阅读
- Python3常用到的函数总结|Python实战项目—金融量化分析(数据的简单预处理)
- 胡希恕《常见病辨证用方提纲》(十六)急慢性肾炎
- kaggle|word2vec和常见CNN+RNN网格结构组成的文本分类模型
- 深度学习与神经网络|第3周 用1层隐藏层的神经网络分类二维数据
- 关于微信小程序使用echarts/数据刷新重新渲染/图层遮挡问题
- echarts几个公司内部数据可视化图表必收藏
- Redis-数据结构详解(下)
- Headless|Headless CMS Sanity 数据建模——定义文档内容的结构
- logstash同步mysql数据到elasticsearch
- 大数据杀熟下的你过得还好吗()