数据处理

/**
 * 返回本周开始日期
 */
- (NSString *)getWeekBegin {
    return [[NSDate getMonthBeginAndEnd:self] objectForKey:@"begin"];
}

+ (NSString *)getWeekBegin:(NSDate *)newDate {
    return [[self getMonthBeginAndEnd:newDate] objectForKey:@"begin"];;
}

/**
 * 返回本周结束日期
 */
- (NSString *)getWeekEnd {
    return [[NSDate getMonthBeginAndEnd:self] objectForKey:@"end"];
}
+ (NSString *)getWeekEnd:(NSDate *)newDate {
    return [[self getMonthBeginAndEnd:newDate] objectForKey:@"end"];;
}

- (NSDictionary *) getMonthBeginAndEnd {
    NSDate *newDate = self;
    if (newDate == nil) {
        newDate = [NSDate date];
    }
    
    double interval = 0;
    NSDate *beginDate = nil;
    NSDate *endDate = nil;
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:2];//设定周一为周首日
    
    BOOL ok = [calendar rangeOfUnit:NSCalendarUnitWeekOfMonth startDate:&beginDate interval:&interval forDate:newDate];
    //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
    if (ok) {
        endDate = [beginDate dateByAddingTimeInterval:interval-1];
    }else {
        return nil;
    }
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    [myDateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *beginString = [myDateFormatter stringFromDate:beginDate];
    NSString *endString = [myDateFormatter stringFromDate:endDate];
    
    return @{@"begin": beginString,
             @"end":endString};
}

你可能感兴趣的:(数据处理)