码迷,mamicode.com
首页 > 其他好文 > 详细

很实用的时间比对算法

时间:2014-05-26 12:40:09      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:style   c   class   blog   code   java   

bubuko.com,布布扣
这个算法很好的解决了闰年的比较,同时也解决了每个月的月初和上个月的末尾不好判断的问题,简单的来说就是用日历和时间差比对
/*
* * 是否为今天 */ - (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; } - (NSDate *)dateWithYMD { NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; fmt.dateFormat = @"yyyy-MM-dd"; NSString *selfStr = [fmt stringFromDate:self]; return [fmt dateFromString:selfStr]; } /** * 是否为今年 */ - (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; } - (NSDateComponents *)deltaWithNow { NSCalendar *calendar = [NSCalendar currentCalendar]; int unit = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond; return [calendar components:unit fromDate:self toDate:[NSDate date] options:0]; }
bubuko.com,布布扣

 

很实用的时间比对算法,布布扣,bubuko.com

很实用的时间比对算法

标签:style   c   class   blog   code   java   

原文地址:http://www.cnblogs.com/llios/p/3746777.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!