开发者

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

开发者 https://www.devze.com 2023-02-10 00:36 出处:网络
I have the following two objects: An NSString obj开发者_如何学Pythonect with a day of the week, ie Monday, Tuesday, Wednesday, etc.

I have the following two objects: An NSString obj开发者_如何学Pythonect 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


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

精彩评论

暂无评论...
验证码 换一张
取 消