标签:
// // NSDate+Joe.h // WeiBo // // Created by 张秀清 on 15/9/17. // Copyright (c) 2015年 张秀清. All rights reserved. // #import <Foundation/Foundation.h> @interface NSDate (Joe) /** * 是否是今天 */ -(BOOL)isToday; /** * 是否是这个月 */ -(BOOL)isThisYear; /** * 是否是今年 */ -(BOOL)isThisMonth; /** * 是否为昨天 */ - (BOOL)isYesterday; /** * 返回‘YYYY-MM-DD‘的nsdate */ - (NSDate *)dateWithYMD; /** * 返回与当前时间的差距 */ - (NSDateComponents *)deltaWithNow; @end // // NSDate+Joe.m // WeiBo // // Created by 张秀清 on 15/9/17. // Copyright (c) 2015年 张秀清. All rights reserved. // #import "NSDate+Joe.h" @implementation NSDate (Joe) -(BOOL)isToday { NSCalendar *calendar = [NSCalendar currentCalendar]; int NSCalendarUnit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay; //获取当前的年月日 NSDateComponents *nowCps = [calendar components:NSCalendarUnit fromDate:[NSDate date]]; NSDateComponents *selfCps = [calendar components:NSCalendarUnit fromDate:self]; return (nowCps.year == selfCps.year) && (nowCps.month == selfCps.month) && (nowCps.day == selfCps.day); } -(BOOL)isThisMonth { NSCalendar *calendar = [NSCalendar currentCalendar]; int NSCalendarUnit = NSCalendarUnitYear | NSCalendarUnitMonth; //获取当前的年月日 NSDateComponents *nowCps = [calendar components:NSCalendarUnit fromDate:[NSDate date]]; NSDateComponents *selfCps = [calendar components:NSCalendarUnit fromDate:self]; return (nowCps.year == selfCps.year) && (nowCps.month == selfCps.month); } -(BOOL)isThisYear { NSCalendar *calendar = [NSCalendar currentCalendar]; int NSCalendarUnit = NSCalendarUnitYear; //获取当前的年月日 NSDateComponents *nowCps = [calendar components:NSCalendarUnit fromDate:[NSDate date]]; NSDateComponents *selfCps = [calendar components:NSCalendarUnit fromDate:self]; return nowCps.year == selfCps.year; } /** * 是否为昨天 */ - (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; } /** * 返回‘YYYY-MM-DD‘的nsdate */ - (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
标签:
原文地址:http://www.cnblogs.com/sixindev/p/4819949.html