1

I have the following two objects: An NSString object with a day of the week, ie Monday, Tuesday, Wednesday, etc. An NSDate object that was saved from a UIDatePicker with UIDatePickerModeTime.

I need to create a third object, NSDate that is the next occurance of the NSString with the time from the NSDate.

//Ex. Tuesday
NSString *confessOn = [[NSUserDefaults standardUserDefaults] objectForKey:kRemindToConfessOn];

//Ex. 2011-02-11 20:13:19
NSDate *confessAt = [[NSUserDefaults standardUserDefaults] objectForKey:kRemindToConfessAt];

NSDate *fireDate = //should be an NSDate with the value 2011-02-15 20:13:19
Travis
  • 5,021
  • 2
  • 28
  • 37

1 Answers1

1
NSDateFormatter * df = [[[NSDateFormatter alloc] init] autorelease];
[df setLocale:[[[NSLocale alloc] initWithLocaleIdentifier(@"en")] autorelease];
[df setDateFormat:@"EEEE"];
NSDate *confessOnDate = [df dateFromString:confessOn];
NSCalendar *cal = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *confessOnComps = [cal components:NSWeekdayCalendarUnit fromDate:confessOnDate];
NSDateComponents *confessAtComps = [cal components:NSWeekdayCalendarUnit fromDate:confessAt];
NSInteger weekdayDifference = ([confessOnComps weekday] + 7 - [confessAtComps weekday]) % 7;
NSDate *fireDate = [confessAt dateByAddingTimeInterval:weekdayDifference * 86400];
Ole Begemann
  • 135,006
  • 31
  • 278
  • 256