【问题标题】:Change NSDate to Friday of that Week将 NSDate 更改为该周的星期五
【发布时间】:2015-03-04 16:02:16
【问题描述】:

目前我有以下代码可以将我的天数增加到下一个星期五,但是我需要的是获得本周的星期五。例如,如果是上周日,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;
}

【问题讨论】:

    标签: objective-c nsdate nsdatecomponents nsdatecomponent


    【解决方案1】:

    尝试使用 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];
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-05
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      • 2019-09-30
      • 2023-03-30
      • 1970-01-01
      相关资源
      最近更新 更多