IOS 根据日期获取该日期所在周,月,年的开始日期,结束日期 的方法

- (void)getMonthBeginAndEndWith:(NSDate *)newDate{
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:NSMonthCalendarUnit startDate:&beginDate interval:&interval forDate:newDate];

//分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit

if (ok) {

endDate = [beginDate dateByAddingTimeInterval:interval-1];

}else {

return;

}

NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];

[myDateFormatter setDateFormat:@"yyyy.MM.dd"];

NSString *beginString = [myDateFormatter stringFromDate:beginDate];

NSString *endString = [myDateFormatter stringFromDate:endDate];

NSString *s = [NSString stringWithFormat:@"%@-%@",beginString,endString];

NSLog(@"%@",s);

}
//是否在同一周
- (BOOL)isSameWeek:(NSDate *)date
{

     NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components:NSCalendarUnitWeekOfYear fromDate:date];
    NSDateComponents *selfComps = [calendar components:NSCalendarUnitWeekOfYear fromDate:[NSDate date]];
    NSInteger week = [comps weekOfYear];//今年的第几周
    NSInteger week2 = [selfComps weekOfYear];

    return week==week2;
}

你可能感兴趣的:(IOS 根据日期获取该日期所在周,月,年的开始日期,结束日期 的方法)