获取前一个工作日

Get previous working day

我需要从当前日期获取上一个工作日期。例如,如果当前日期是星期一,我需要获取星期五的日期。

我有以下代码可以从当前日期获取上一个日期。

-(NSDate*)previousDateFromDate:(NSDate*)date {

NSDate *now = date;
int daysToAdd = -1;

// set up date components
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:daysToAdd];

// create a calendar
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:GregorianCalendar];
return [gregorian dateByAddingComponents:components toDate:now options:0];

}

我怎样才能做到这一点?是通过计算当日指数的差异吗?

-(NSDate*)previousDateFromDate:(NSDate*)date {

    NSCalendar* cal = [NSCalendar currentCalendar];
    NSDateComponents* comp = [cal components:NSWeekdayCalendarUnit fromDate:date];

    //[comp weekday] =  1 = Sunday, 2 = Monday, etc.

    NSDate * returnDate;

    if([comp weekday] == 1){
        returnDate = [[NSDate date]dateByAddingTimeInterval:(-86400 * 2)];
    }else {
        returnDate = [[NSDate date]dateByAddingTimeInterval:-86400];
    }
    return returnDate;
}

你的想法是正确的,使用星期几是正确的方法,代码中的注释:

-(NSDate*)previousDateFromDate:(NSDate*)date
{
   // Get the current calendar
   NSCalendar *currentCal = [NSCalendar currentCalendar];

   // Get current weekday, Sunday = 1
   NSDateComponents *comps = [currentCal components:NSWeekdayCalendarUnit fromDate:date];
   NSInteger weekday = comps.weekday;

   // Determine the number of days to go back, assuming Sat -> Mond should go to Fri
   NSInteger deltaDays = weekday == 1 ? -2 : (weekday == 2 ? -3 : -1);

   // Create componets with the offset
   NSDateComponents *offset = [NSDateComponents new];
   offset.day = deltaDays;

   // Calculate the required date
   return [currentCal dateByAddingComponents:offset toDate:date options:0];
}

这假设当前日历是公历,您必须弄清楚它是否适用于其他日历。

HTH