Reputation: 5801
I need to get previous working date from the current date. For instance if the current day is monday , I need to get the date of Friday .
I have following code to get the previous date from the current date.
-(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];
}
How can I achieve this ? Is it by calculating difference of index of the current day ?
Upvotes: 0
Views: 256
Reputation: 53000
You've got the right idea and using the weekday number is the way to go, comments in code:
-(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];
}
This assumes the current calendar is the Gregorian one, you'll have to figure out if it works for others.
HTH
Upvotes: 1
Reputation: 3283
-(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;
}
Upvotes: 0