NSDate的使用方便的分类(提供判断是否为今天,昨天,今年的方法)
分类的.h文件提供四个方法来方便使用
- (BOOL)isToday;//判断是否为今天
- (BOOL)isYesterday;//是否为昨天
- (BOOL)isThisYear;//是不是今年
- (NSDate *)dateWithYMD;//格式化日期,返回yyyy-MM-dd
- (NSDateComponents *)deltaWithNow;//日期和当前日期的差的天数
方法的具体实现
- (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);
}
//格式化日期
- (NSDate *)dateWithYMD
{
NSDateFormatter *fmt = [[NSDateFormatteralloc] init];
fmt.dateFormat = @"yyyy-MM-dd";
NSString *selfStr = [fmt stringFromDate:self];
return [fmt dateFromString:selfStr];
}
//判断是不是今年
-(BOOL)thisYear
{
NSCalendar *cale = [NSCalendar curentCalendar];
int unit = NSCalendarUnitYear;
//获取当前的年月日
NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date];
//获得self的年月日
NSDateComponents *selfCmps = [calendar components:unit fromDate:self];
return nowCmps.year == selfCmps.year;
}
//计算日期差
- (NSDateComponents *)deltaFromNow
{
NSCalendar *calendar = [NSCalendar currentCalendar];
int unit = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
return [calendar components:unit fromDate:selftoDate:[NSDatedate] options:0];
}
2014年05月12日07:37:12
mark - All right reserved.