1、需要创建一个NSDate类的category,调用的时候需要传进来一个NSDate类型的时间即可返回BOOL值来判断改时间是不是今日等。
2、直接上干货
创建完分类后,在.h文件中加入下面的代码:
#import
@interface NSDate (Extension)
/**
* 是否为今天
*/
- (BOOL)isToday;
/**
* 是否为昨天
*/
- (BOOL)isYesterday;
/**
* 是否为今年
*/
- (BOOL)isThisYear;
/**
* 返回一个只有年月日的时间
*/
- (NSDate *)dateWithYMD;
/**
* 获得与当前时间的差距
*/
- (NSDateComponents *)deltaWithNow;
@end
3、切换到.m文件中,加入下面代码:
#import "NSDate+Extension.h"
@implementation NSDate (Extension)
/**
* 是否为今天
*/
- (BOOL)isToday
{
NSCalendar *calendar = [NSCalendar currentCalendar];
int unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear;
// 1.获得当前时间的年月日
NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];
// 2.获得self的年月日
NSDateComponents *selfCmps = [calendar components:unit fromDate:self];
return
(selfCmps.year == nowCmps.year) &&
(selfCmps.month == nowCmps.month) &&
(selfCmps.day == nowCmps.day);
}
/**
* 是否为昨天
*/
- (BOOL)isYesterday
{
// 2014-05-01
NSDate *nowDate = [[NSDate date] dateWithYMD];
// 2014-04-30
NSDate *selfDate = [self dateWithYMD];
// 获得nowDate和selfDate的差距
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *cmps = [calendar components:NSCalendarUnitDay fromDate:selfDate toDate:nowDate options:0];
return cmps.day == 1;
}
/**
* 是否为今年
*/
- (BOOL)isThisYear
{
NSCalendar *calendar = [NSCalendar currentCalendar];
int unit = NSCalendarUnitYear;
// 1.获得当前时间的年月日
NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];
// 2.获得self的年月日
NSDateComponents *selfCmps = [calendar components:unit fromDate:self];
return nowCmps.year == selfCmps.year;
}
/**
* 返回一个只有年月日的时间
*/
- (NSDate *)dateWithYMD
{
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd";
NSString *selfStr = [fmt stringFromDate:self];
return [fmt dateFromString:selfStr];
}
/**
* 获得与当前时间的差距
*/
- (NSDateComponents *)deltaWithNow
{
NSCalendar *calendar = [NSCalendar currentCalendar];
int unit = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
return [calendar components:unit fromDate:self toDate:[NSDate date] options:0];
}
@end
NSDateFormatter *formater = [[NSDateFormatter alloc] init];
formater.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *sendDate = [formater dateFromString:@"你想判断的时间"];
sendDate . isToday //判断是否为今日sendDate.isThisYear //判断是否为昨日
sendDate.isYesterday //判断是否为今年
还有一个是获取与当前时间差距的方法deltaWithNow
基本上就是这样搞的