Curnelious Curnelious - 4 months ago 12x
Objective-C Question

Setting week day of NSDate will not change the date?

I have some date in which i would like to change its week day to another day, while user do some action.
When i change the week day to another day/days, the result NSDate stay in the same day of the month , so

will stay the same if i set the

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitWeekday|NSCalendarUnitSecond|NSCalendarUnitMonth|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitYear|NSCalendarUnitDay) fromDate:lastdate];
[dateComponents setWeekday:currentDay]; //set it to numbers from 0 to 7
NSDate *date = [calendar dateFromComponents:dateComponents];

NSLog(@"%@",lastdate); //stay the same date of the month although i change the week day .

removing the day unit from the component, will not solve the problem but will create a wrong month day for the new date :

NSLog(@"%@",lastdate);//gives 14.4.15

//change last date day to the new day
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitWeekday|NSCalendarUnitSecond|NSCalendarUnitMonth|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitYear ) fromDate:lastdate];
[dateComponents setWeekday:currentDay];//added one day
NSDate *date = [calendar dateFromComponents:dateComponents];

NSLog(@"%@",lastdate); //gives 1.4.15


I have manage to do that in 3 steps, taking the current date, get its day of month, than calculate days to add, than add them to the new date :

//get new date with the new month day
NSDate *newdate=[[NSDate date] dateByAddingTimeInterval:60*60*24* (currentDay-today) ]; //current day is the day the user chosen . today, is day of today .

//extract the new month day
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitWeekday|NSCalendarUnitSecond|NSCalendarUnitMonth|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitYear|NSCalendarUnitDay ) fromDate:newdate];
long newDayOfMonth=[dateComponents day];

//create components from nob date
 NSDateComponents *nobComponents = [calendar components:(NSCalendarUnitWeekday|NSCalendarUnitSecond|NSCalendarUnitMonth|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitYear|NSCalendarUnitDay ) fromDate:lastdate];
[nobComponents setDay:newDayOfMonth];
 NSDate *date = [calendar dateFromComponents:dateComponents];

NSLog(@"final date:%@",lastdate);