iOS判断两个日期是否为同一周

星期一到星期天为一周,创建NSDate扩展类
NSDate+ Helper.h文件代码如下:

#import 

#define D_MINUTE  60
#define D_HOUR    3600
#define D_DAY     86400
#define D_WEEK    604800

@interface NSDate (Helper)

@property (readonly) NSInteger weekday;         // 系统默认weekday:星期日对应weekday=1
@property (readonly) NSInteger customWeekday;   // 中国weekday:星期一对应weekday=1

+ (NSCalendar *)currentCalendar;
// 判断两个日期是否为同一周的方法
- (BOOL)isSameWeekAsDate:(NSDate *)anotherDate;

@end

NSDate+Helper.m文件代码如下:

#import "NSDate+Helper.h"

static const unsigned componentFlags = (NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekday | NSCalendarUnitWeekdayOrdinal | NSCalendarUnitWeekOfMonth | NSCalendarUnitWeekOfYear | NSCalendarUnitQuarter);

@implementation NSDate (Helper)

#pragma mark - Public Method
+ (NSCalendar *) currentCalendar
{
    static NSCalendar *sharedCalendar = nil;
    if (!sharedCalendar)
        sharedCalendar = [NSCalendar autoupdatingCurrentCalendar];
    return sharedCalendar;
}

- (BOOL) isSameWeekAsDate:(NSDate *)otherDate
{
    BOOL result = NO;
    
    NSTimeInterval startInterval = [self timeIntervalAtStartOfDaySince1970];
    NSTimeInterval endInterval = [self timeIntervalAtEndOfDaySince1970];
    NSTimeInterval otherInterval = [otherDate timeIntervalSince1970];
    NSUInteger weekday = [self customWeekday];
    startInterval = startInterval - (weekday-1) * D_DAY;
    endInterval = endInterval + (7-weekday) * D_DAY;
    if (otherInterval >= startInterval && otherInterval <= endInterval) {
        result = YES;
    }
    
    return result;
}

#pragma mark - Private Method
- (NSDate *) dateAtStartOfDay
{
    NSDateComponents *components = [[NSDate currentCalendar] components:componentFlags fromDate:self];
    components.hour = 0;
    components.minute = 0;
    components.second = 0;
    return [[NSDate currentCalendar] dateFromComponents:components];
}

- (NSDate *) dateAtEndOfDay
{
    NSDateComponents *components = [[NSDate currentCalendar] components:componentFlags fromDate:self];
    components.hour = 23;
    components.minute = 59;
    components.second = 59;
    return [[NSDate currentCalendar] dateFromComponents:components];
}

- (NSTimeInterval)timeIntervalAtStartOfDaySince1970
{
    return [[self dateAtStartOfDay] timeIntervalSince1970];
}

- (NSTimeInterval)timeIntervalAtEndOfDaySince1970
{
    return [[self dateAtEndOfDay] timeIntervalSince1970];
}

#pragma mark - getter or setter
- (NSInteger) weekday
{
    NSDateComponents *components = [[NSDate currentCalendar] components:componentFlags fromDate:self];
    return components.weekday;
}

- (NSInteger)customWeekday
{
    NSDateComponents *components = [[NSDate currentCalendar] components:componentFlags fromDate:self];
    return components.weekday==1 ? 7 : --components.weekday;
}

@end

你可能感兴趣的:(iOS判断两个日期是否为同一周)