1

我有以下两个对象: 一个带有一周中某一天的 NSString 对象,即星期一、星期二、星期三等。一个 NSDate 对象是从具有 UIDatePickerModeTime 的 UIDatePicker 中保存的。

我需要创建第三个对象,NSDate,它是 NSString 的下一次出现,时间来自 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
4

1 回答 1

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];
于 2011-02-13T15:43:13.243 回答