【问题标题】:Combing NSString with the day of week and NSDate with the time into an NSDate object将 NSString 与星期几和 NSDate 与时间组合成一个 NSDate 对象
【发布时间】:2011-02-13 10:10:17
【问题描述】:

我有以下两个对象: 一个带有星期几的 NSString 对象,即星期一、星期二、星期三等。 使用 UIDatePickerModeTime 从 UIDatePicker 保存的 NSDate 对象。

我需要创建第三个对象,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

【问题讨论】:

    标签: objective-c cocoa-touch nsdate uidatepicker uidatepickermodetime


    【解决方案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];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 2012-06-26
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      相关资源
      最近更新 更多