您好我使用此代码获取开始日期和结束日期。但是,如果我选择星期天它会在下周继续运行并在下周给我结果。
请通过选择星期日来建议我如何获得适当的结果。
提前谢谢。NSDate *today = date;
NSLog(@"Today date is %@",today);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];// you can use your format.
//Week Start Date
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:today];
NSInteger dayofweek = [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:today] weekday];// this will give you current day of week
[components setDay:([components day] - ((dayofweek) - 2))];// for beginning of the week.
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:@"yyyy-MM-dd"];
NSString *dateString2Prev = [dateFormat stringFromDate:beginningOfWeek];
NSDate *weekstartPrev = [dateFormat_first dateFromString:dateString2Prev];
// NSDate *weekEndPrev = [dateFormat_End dateFromString:dateEndPrev];
NSDateFormatter *dateFf = [[NSDateFormatter alloc] init];
[dateFf setDateFormat:@"MM/dd/yyyy"];
strStartDate = [dateFf stringFromDate:weekstartPrev];
NSLog(@"%@",strStartDate);
//Week End Date
NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *componentsEnd = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:today];
NSInteger Enddayofweek = [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:today] weekday];// this will give you current day of week
[componentsEnd setDay:([componentsEnd day]+(7-Enddayofweek)+1)];// for end day of the week
NSDate *EndOfWeek = [gregorianEnd dateFromComponents:componentsEnd];
NSDateFormatter *dateFormat_End = [[NSDateFormatter alloc] init];
[dateFormat_End setDateFormat:@"yyyy-MM-dd"];
NSString *dateEndPrev = [dateFormat stringFromDate:EndOfWeek];
NSDate *weekEndPrev = [dateFormat_End dateFromString:dateEndPrev];
NSDateFormatter *dateF = [[NSDateFormatter alloc] init];
[dateF setDateFormat:@"MM/dd/yyyy"];
strEndDate = [dateF stringFromDate:weekEndPrev];
NSString *showStartDate = [self setAPIDateFormat:weekstartPrev:@"MMMM dd, yyyy"];
NSString *showEndDate =[self setAPIDateFormat:weekEndPrev:@"MMMM dd, yyyy"];
_lblStartEnd.text = [NSString stringWithFormat:@"%@ - %@",showStartDate,showEndDate];
datesArray =[[NSMutableArray alloc]init];
// NSDate *startD = [[NSDate date] dateByAddingTimeInterval: -86400.0];
datesArray = [self getDatesArrayBetweenTwoDates:[weekstartPrevdateByAddingTimeInterval: -86400.0] andEndDate:weekEndPrev];
[_Workdiscription reloadData];