Combing NSString with the day of week and NSDate with the time into an NSDate object

359 Views Asked by At

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
1

There are 1 best solutions below

0
On
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];