I need to set UILocalNotification, I just need to take hour and minute from DatePicker and need to set specific date ( like : Monday ) and repeat it on every Monday.>
Here's @iPatel's solution that also factors in the time component passed in via the datepicker. (I also updated his solution to use the latest calendar units that aren't deprecated).
- (NSDate *) getFireDateForDayOfWeek:(NSInteger)desiredWeekday withTime:(NSDate *)time // 1:Sunday - 7:Saturday
{
NSRange weekDateRange = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSCalendarUnitWeekday];
NSInteger daysInWeek = weekDateRange.length - weekDateRange.location + 1;
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:[NSDate date]];
NSInteger currentWeekday = dateComponents.weekday;
NSInteger differenceDays = (desiredWeekday - currentWeekday + daysInWeek) % daysInWeek;
NSDateComponents *daysComponents = [[NSDateComponents alloc] init];
daysComponents.day = differenceDays;
NSDate *fireDate = [[NSCalendar currentCalendar] dateByAddingComponents:daysComponents toDate:[NSDate date] options:0];
NSDateComponents *timeComponents = [[NSCalendar currentCalendar] components: NSCalendarUnitHour | NSCalendarUnitMinute fromDate:time];
NSDateComponents *fireDateComponents = [[NSCalendar currentCalendar]
components: NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond
fromDate:fireDate];
fireDateComponents.hour = timeComponents.hour;
fireDateComponents.minute = timeComponents.minute;
fireDateComponents.second = 0;
NSDate *resultDate = [[NSCalendar currentCalendar] dateFromComponents:fireDateComponents];
// The day could be today but time is in past. If so, move ahead to next week
if(resultDate.timeIntervalSinceNow < 0) {
resultDate = [resultDate dateByAddingTimeInterval:60 * 60 * 24 * 7];
}
return resultDate;
}