我需要从当前日期开始上一个工作日期。例如,如果当天是星期一,我需要得到星期五的日期。
我有以下代码来获取当前日期的上一个日期。
-(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];
}
我怎样才能做到这一点?是通过计算当天指数的差异?
答案 0 :(得分:1)
你有正确的想法,使用工作日号是要走的路,代码中的评论:
-(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
答案 1 :(得分: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;
}