iOS学习-NSString与NSDate的相互转换

NSDate转换为NSString

//获取系统当前时间
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];

NSString转换为NSDate

NSString * timeStr = @"2019-11-06"; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//需要设置为和字符串相同的格式
[dateFormatter setDateFormat:@"yyyy-MM-dd"]; 
NSDate *localDate = [dateFormatter dateFromString:timeStr];

猜你喜欢

转载自blog.csdn.net/qq_43441647/article/details/129283571