2012-04-03 42 views
0

我有一個的UIDatePicker,我用這個獲取日期:格式的UIDatePicker另一個NSDate的

NSDate *pickerDate = [datePickerView date]; 

我想創造一種是基於星期和時間的天將來的日期(HH :mm:ss)從pickerDate。下面是我使用的代碼,但它生成的日期是錯誤的:

更新的代碼

 //format the uidatepicker 
     NSDate *dateSet = pickerDate; 
     NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
     [df setTimeZone:[NSTimeZone localTimeZone]]; 
     [df setDateFormat:@"EEEE HH:mm:ss"]; 
     NSString *dateSetString = [df stringFromDate:dateSet]; 

     NSLog(@"repeatDateString %@",dateSetString);//prints "Tuesday 12:12:43" 

     //create a new nsdate using the new format 
     NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init]; 
     [dateFormat2 setTimeZone:[NSTimeZone localTimeZone]]; 
     [dateFormat2 setDateFormat: @"EEEE HH:mm:ss"]; 

     NSDate *newDate = [[NSDate alloc] init]; 
     newDate = [dateFormat2 dateFromString:dateSetString]; 

     NSLog(@"new Date %@",newDate);//prints "1970-01-06 04:42:43 +0000" 

回答

1

的問題是,你的日期字符串不包含所有的信息,從選擇器,並且沒有包含足夠的信息來重新創建日期。它錯過了日,月和年,所以當你重新創建它時,它假定你想從iOS的NSDate日曆系統開始。

您或者需要存儲從選取器(最好)收到的NSDate,或者您需要使用包含足夠信息的日期格式來創建特定的日期和時間。

編輯
基於您的評論,你只想使用從日期選擇在工作日和時間,並決定在未來與這些值的下一個日期。這裏是代碼將實現:

NSCalendar   *cal   = [NSCalendar currentCalendar]; 

NSDate    *pickerDate  = self.datePickerView.date; 
NSDateComponents *pickerComps = [cal components: NSWeekdayCalendarUnit | 
                 NSHourCalendarUnit | 
                 NSMinuteCalendarUnit | 
                 NSSecondCalendarUnit 
              fromDate:pickerDate]; 

NSDate    *currentDate = [NSDate date]; 
NSDateComponents *currentComps = [cal components: NSYearCalendarUnit | 
                 NSMonthCalendarUnit | 
                 NSWeekdayCalendarUnit | 
                 NSDayCalendarUnit | 
                 NSHourCalendarUnit | 
                 NSMinuteCalendarUnit | 
                 NSSecondCalendarUnit 
              fromDate:currentDate]; 

// Start with the current date and add/subtract the number of days needed to make it the same day of the week 
NSDateComponents *newComps  = [currentComps copy]; 
NSUInteger   weekdayDiff  = pickerComps.weekday - currentComps.weekday; 
newComps.day      = newComps.day + weekdayDiff; 
// If needed, add 7 days in order to move this date into the future 
if (newComps.day < currentComps.day) { 
    newComps.day = newComps.day + 7; 
} 

NSDate *newDate = [cal dateFromComponents:newComps]; 
if ([newDate compare:currentDate] == NSOrderedAscending) { 
    // This is true when the weekday started out the same but the time of day is earlier in the picker. 
    // Add 7 days 
    newComps.day = newComps.day + 7; 
    newDate = [cal dateFromComponents:newComps]; 
} 

NSLog(@"%@", newDate); 
+0

我明白了。其實我設置了一個日期,我將使用我的localnotification的repeatInterval和Im使用NSWeekCalendarUnit。所以我想在特定的日期和時間使用日期重複我的通知,這就是爲什麼我想要創建一個nsdate,就像我在代碼中一樣。有沒有更好的方法呢? – Diffy 2012-04-03 04:13:55

+0

那麼你最終想要結束的是「下一個星期二12:12:43」(從現在開始)? – lnafziger 2012-04-03 04:19:04

+0

是的。這就是我想要的。 – Diffy 2012-04-03 04:25:45