日期转换
- (void)viewDidLoad { [super viewDidLoad]; NSDate *currentDate = [NSDate date]; //传入一个日期 判断这个日期是今天 明天 还是昨天 [self compareDate:currentDate]; //传入今天的时间,返回今天后14天的时间 for (int i=1; i<15; i++) { NSLog(@"========%@日",[self GetTomorrowDay:currentDate index:i]); }
NSLog(@"获取当地时间===%@",[self getCurrentTime]); }
//获取当地时间 - (NSString *)getCurrentTime { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy-MM-dd"]; NSString *dateTime = [formatter stringFromDate:[NSDate date]]; return dateTime; } //将字符串转成NSDate类型 - (NSDate *)dateFromString:(NSString *)dateString { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat: @"yyyy-MM-dd"]; NSDate *destDate= [dateFormatter dateFromString:dateString]; return destDate; } //传入今天的时间,返回今天后多少天的时间 (返回明天的时间 index=1) - (NSString *)GetTomorrowDay:(NSDate *)aDate index:(NSInteger)index{ NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate]; [components setDay:([components day]+index)]; NSDate *beginningOfWeek = [gregorian dateFromComponents:components]; NSDateFormatter *dateday = [[NSDateFormatter alloc] init]; [dateday setDateFormat:@"MM-dd"]; return [dateday stringFromDate:beginningOfWeek]; } // 传入一个日期 判断这个日期是今天 明天 还是昨天 -(NSString *)compareDate:(NSDate *)data{ NSTimeInterval secondsPerDay=24*60*60; NSDate *today=[[NSDate alloc]init]; NSDate *tomorrow,*yesterday; tomorrow=[today dateByAddingTimeInterval:secondsPerDay]; yesterday=[today dateByAddingTimeInterval:-secondsPerDay]; NSString *todayString=[[today description]substringToIndex:10]; NSString *yesterdayString=[[today description]substringToIndex:10]; NSString *tomrrowString=[[today description]substringToIndex:10]; NSString *dateString =[[data description]substringToIndex:10]; if ([dateString isEqualToString:todayString]) { return @"今天"; }else if ([dateString isEqualToString:yesterdayString]){ return @"昨天"; }else if ([dateString isEqualToString:tomrrowString]){ return @"明天"; }else{ NSLog(@"%@",dateString); return dateString; } }
有疑问可以联系我哦 1165300131