目前我有以下代码将我的日子增加到下一个星期五,但我需要的是获得当周的星期五。例如,如果它是03/01的最后一个星期日。我希望我的回复是上周五(02/28),而不是周五(03/06)。
我已经检查了其他答案,但我对如何实现一种干净的方法来解决这个问题感到困惑。
+ (NSDate *)getLastFridayYearsMonthStartingDate:(NSDate *)date {
NSDateComponents *dateComponents = [[NSCalendar gregorianCalendar] components:NSYearCalendarUnit|NSCalendarUnitDay|NSCalendarUnitMonth|NSWeekdayCalendarUnit
fromDate:date];
// Set date to last year, +1 to account for previous business day
[dateComponents setYear: -1];
[dateComponents setDay:[dateComponents day]+1];
// We always want the start date to be the friday of the given week, so we will increment the difference if not
if ([dateComponents weekday] != 6) {
NSInteger daysToFriday = (13 - [dateComponents weekday]) % 7;
[dateComponents setDay:[dateComponents day]+daysToFriday];
}
NSDate *fridayDate = [[NSCalendar gregorianCalendar] dateFromComponents:dateComponents];
return fridayDate;
}
答案 0 :(得分:0)
尝试使用setWeekday设置特定日期
-(NSDate *) getFriday:(NSDate *)date {
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone systemTimeZone]];
NSDateComponents *comp = [cal components:NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:date];
[comp setWeekday:6];
[comp setHour:0];
[comp setMinute:0];
[comp setSecond:0];
return [cal dateFromComponents:comp];
}