判断是否为今年
- 取出日期的年份进行比较,如果一样返回1,不一样就返回0。
- (BOOL) isThisYear{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger *nowYear = (NSInteger *)[calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
NSInteger *selfYear = (NSInteger *)[calendar component:NSCalendarUnitYear fromDate:self];
return nowYear == selfYear;
}
判断是否为今天
- 取出当前日期和要比较日期的年月日,并将它们的类型从Date类型转成NSString类型,然后判断2者是否相等,相等返回1,不相等返回0。
- (BOOL) isToday{
NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
fmt.dateFormat = @"yyyy-mm-dd";
NSString *nowDay = [fmt stringFromDate:[NSDate date]];
NSString *selfDay = [fmt stringFromDate:self];
return [nowDay isEqualToString:selfDay];
}
判断是否为昨天
- 取出当前日期和要比较日期的年月日,并将它们的类型从Date类型转成NSString类型,然后再将NSString类型转回Data类型,然后用[calendar components:NSCalendarUnitDay fromDate:selfDate toDate:nowDate options:0]来比较要比较的日期和当前日期相差多少天,如果components.year == 0 && components.month == 0 && components.day == 1;
则返回 1,否则返回0。
- (BOOL) isYesterday{
NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
fmt.dateFormat = @"yyyy-mm-dd";
NSDate *nowDate = [fmt dateFromString:[fmt stringFromDate:[NSDate date]]];
NSDate *selfDate = [fmt dateFromString:[fmt stringFromDate:self]];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitDay fromDate:selfDate toDate:nowDate options:0];
return components.year == 0
&& components.month == 0
&& components.day == 1;
}
网友评论