iOS NSDate计算、比较

1.计算两个日期相差多少天

//创建两个日期
+ (NSInteger)intervalDayFromBetween:(NSString *)day day2:(NSString *)day2{
//创建两个日期
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *startDate = [dateFormatter dateFromString:day];
NSDate *endDate = [dateFormatter dateFromString:day2];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *delta = [calendar components:NSCalendarUnitDay fromDate:startDate toDate:endDate options:0];
return delta.day;
}

2.在原有日期上加减N天

+ (NSString *)datePlus:(NSString *)dateStr interval:(NSInteger)interval{
NSDateFormatter *format=[[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd"];
NSDate * oldDate=[format dateFromString:dateStr];
newDate = [oldDate dateByAddingTimeInterval:24 * 60 * 60 * (interval)];
return [format stringFromDate:newDate];
}

3.获取日期是星期几

//获取dateStr是星期几
+ (NSInteger)getweekDayStringWithDate:(NSString *)dateStr{
NSDateFormatter *format=[[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd"];
NSDate *newDate=[format dateFromString:dateStr];
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // 指定日历的算法
NSDateComponents *comps = [calendar components:NSWeekdayCalendarUnit fromDate:newDate];// 1 是周日,2是周一 3.以此类推
NSInteger weekDay = comps.weekday-1 == 0?7:comps.weekday-1;
return weekDay;
}

4.获取日期的月初和月末

+ (NSArray *)getMonthFirstAndLastDayWith:(NSString *)dateStr{
NSDateFormatter *format=[[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd"];
NSDate *newDate=[format dateFromString:dateStr];
double interval = 0;
NSDate *firstDate = nil;
NSDate *lastDate = nil;
NSCalendar *calendar = [NSCalendar currentCalendar];
BOOL OK = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:&firstDate interval:&interval forDate:newDate];
if (OK) {
lastDate = [firstDate dateByAddingTimeInterval:interval - 1];
}else {
return @[@"",@""];
}
NSString *firstString = [format stringFromDate:firstDate];
NSString *lastString = [format stringFromDate:lastDate];
return @[firstString, lastString];
}

5.判断day日期是否在start和end之间

//day日期在Start与end之间
+ (BOOL)inPeriod:(NSString *)day start:(NSString *)start end:(NSString *)end {
return [day isEqualToString:start] || [day isEqualToString:end]
|| (![self checkProductDate:day date2:start] && [self checkProductDate:day date2:end]);
}

+ (BOOL)checkProductDate:(NSString *)date1str date2:(NSString *)date2str{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date1 = [dateFormatter dateFromString:date1str];
NSDate *date2 = [dateFormatter dateFromString:date2str];
// 判断是否大于当前时间
if ([date1 earlierDate:date2] != date1) {
return YES;
}else{
return NO;
}
}

你可能感兴趣的:(iOS NSDate计算、比较)