NSDate的一个分类,判断是否是今天,昨天,今年,获得与当前时间的差距,返回一个只有年月日的日期
2015-09-14 19:47
706 查看
// // NSDate+YKD.h #import <Foundation/Foundation.h> @interface NSDate (YKD) /** * 是否为今天 */ - (BOOL)isToday; /** * 是否为昨天 */ - (BOOL)isYesterday; /** * 是否为今年 */ - (BOOL)isThisYear; /** * 获得与当前时间的差距 */ - (NSDateComponents *)deltaWithNow; /** * 返回一个只有年月日的时间 */ - (NSDate *)dateWithYMD; @end
#import "NSDate+YKD.h" @implementation NSDate (YKD) - (BOOL)isToday { //now: 2015-09-05 11:23:00 //self 调用这个方法的对象本身 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 selfCmps.year == nowCmps.year; } /** * 返回这种格式的日期 yyyy-MM-dd */ - (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
相关文章推荐
- LeetCode OJ4 Median of Two Sorted Arrays 小结
- 最长公共子序列
- hdu5444 Elven Postman
- Android Studio(八):Android Studio设置教程
- Android Studio(八):Android Studio设置教程
- Retrofit中使用GSON解析定制格式的JSON
- 电子商务模式汇总
- 最大子段和暴力求解
- 递归
- DbUtils在SQLite中的应用
- webapi ,前台json传入raw读取
- maven 安装jar包命令
- HDU 1950 Bridging signals ( DP动态规划 O(n^2) )
- leetcode 220 Contains Duplicate III
- The Water Problem(RMQ)
- 整数划分问题
- 【Java EE 学习 43】【SVN版本控制工具】【CVS版本控制工具】
- Java IO读写大文件的几种方式及测试
- 我是如何自学Android,资料分享(2015 版)
- 矩阵乘法