将 NSDate 更改为该周的星期五
Change NSDate to Friday of that Week
目前我有下面的代码可以将我的天数增加到下一个星期五,但是我需要的是获取本周的星期五。例如,如果是上周日,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;
}
尝试使用 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];
}
目前我有下面的代码可以将我的天数增加到下一个星期五,但是我需要的是获取本周的星期五。例如,如果是上周日,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;
}
尝试使用 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];
}