iOS开发——比较两个日期相差多少天(月、年)
iOS开发——比较两个日期相差多少天(月、年)
根据两个日期(NSDate),算出它们相差多少天。
//创建两个日期
- (int)twoDateDifferenceDay{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *startDate = [dateFormatter dateFromString:@"2019-11-13"];
NSDate *endDate = [dateFormatter dateFromString:@"2020-01-24"];
//利用NSCalendar比较日期的差异
NSCalendar *calendar = [NSCalendar currentCalendar];
/**
* 要比较的时间单位,常用如下,可以同时传:
* NSCalendarUnitDay : 天
* NSCalendarUnitYear : 年
* NSCalendarUnitMonth : 月
* NSCalendarUnitHour : 时
* NSCalendarUnitMinute : 分
* NSCalendarUnitSecond : 秒
*/
NSCalendarUnit unit = NSCalendarUnitDay;//只比较天数差异
//NSCalendarUnit unit1 = NSCalendarUnitDay | NSCalendarUnitMonth;//同时比较天数、月份差异
//比较的结果是NSDateComponents类对象
NSDateComponents *delta = [calendar components:unit fromDate:startDate toDate:endDate options:0];
//打印
NSLog(@"%@",delta);
//获取其中的"天"
NSLog(@"%ld",delta.day);
//计算当前日期是星期几
- (NSString *)judgeCurrentDateIsWeekDay:(NSDate *)startDate{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormattersetDateFormat:@"YYYY-MM-dd"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps;
comps = [calendarcomponents:(NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekday |NSCalendarUnitWeekdayOrdinal) fromDate:startDate];
NSInteger weekday = [comps weekday];
NSArray*weekdays = [NSArray arrayWithObjects: [NSNull null],@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六",nil];
NSString *weekStr = [weekdays objectAtIndex:weekday];
NSString *startTime = [dateFormatter stringFromDate:startDate];
startTime = [startTimesubstringToIndex:10];
NSLog(@"%@ %@",startTime,weekStr);
return startTime;
}