(一) 获取NSDate的当前年月日
- NSDateFormat获取
NSDate *date =[NSDate date];//简书 FlyElephant
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy"];
NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
[formatter setDateFormat:@"MM"];
NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
[formatter setDateFormat:@"dd"];
NSInteger currentDay=[[formatter stringFromDate:date] integerValue];
- NSDateComponents获取
NSDate *currentDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];
NSInteger year=[components year];
NSInteger month=[components month];
NSInteger day=[components day];
(二)获取当前时间
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//现在时间,你可以输出来看下是什么格式
NSDate *datenow = [NSDate date];
//将nsdate按formatter格式转成nsstring
NSString *currentTimeString = [formatter stringFromDate:datenow];