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 13.4.15
will stay the same if i set the dayweek
to 5
.
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];
lastdate=date;
NSLog(@"%@",lastdate); //stay the same date of the month although i change the week day .
EDIT: 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];
lastdate=date;
NSLog(@"%@",lastdate); //gives 1.4.15