2012-02-03 98 views
0

我正在創建一個簡單的鬧鐘應用程序。問題是我在日誌中得到錯誤的輸出日期,我不知道爲什麼。請嘗試解決我的問題。下面是我的代碼:執行代碼時給出的錯誤時間

下面的代碼是使用到init方法則是能正常工作,而我使用下面的代碼到我的viewDidLoad那麼它不工作

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar]; 

// Get the current date 
NSDate *pickerDate = [self.datePicker date]; 

// Break the date up into components 
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) 
               fromDate:pickerDate]; 
NSDateComponents *timeComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) 
               fromDate:pickerDate]; 


NSDateComponents *dateComps = [[NSDateComponents alloc] init]; 
[dateComps setDay:[dateComponents day]]; 
[dateComps setMonth:[dateComponents month]]; 
[dateComps setYear:[dateComponents year]]; 
[dateComps setHour:[timeComponents hour]]; 

[dateComps setMinute:[timeComponents minute]]; 
[dateComps setSecond:[timeComponents second]]; 
NSDate *itemDate = [calendar dateFromComponents:dateComps]; 
     NSLog(@"date components are:>>%@",dateComps); 
NSLog(@"Item date is ::>>%@",itemDate); 


[dateComps release]; 

處在於:在打印對象比顯示錯誤的日期和時區在這裏發佈白羊座。 請幫助解決這個問題

@samuel

回答

0

許多搜索找到該

當任何日期挑入pickerviewcontroller的原因後,總是隻擊掌+ 000 GMT格式

如果我們需要與最新的本地時區轉換爲我們需要的將dateformater類用於該項目的下面的代碼。

NSDateFormatter* df_local = [[NSDateFormatter alloc] init]; 
[df_local setTimeZone:[NSTimeZone localTimeZone]]; 
[df_local setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
// [df_local stringFromDate:date]; 

NSString *strForArr=[self.arForSubTitle objectAtIndex:0]; 
NSString *newStr = [strForArr substringToIndex:[strForArr length]-5]; 
NSDate *theDate = [df_local dateFromString:newStr];   

NSLog(@"%@",[theDate description]); 

感謝和問候

@samuel。

0

嘗試輸入:

NSDate *pickerDate = [NSDate date]; 

,以確認它不是一個問題,您的代碼。如果你在NSLog中得到了正確的日期,那麼你的代碼就可以了,問題可能出在你可能使用的UIDatePicker控件上?那麼試試吧

NSDate *pickerDate = [self.datePicker date]; 
NSLog(@"Date = %@", pickerDate); 

來驗證你是否從日期選取器控制中獲得正確的值。

該代碼應放置在您的viewDidLoad方法中。我從上面精確地複製了你的代碼,它完全適用於我的應用程序。

問題:你是說你的代碼完全可以在init中工作,但是在viewDidLoad方法中工作不正確?