2012-01-04 91 views
3

我正嘗試初始化一個UIDatePicker,該日期在我的會話中早些時候從那個日期選擇器返回給我。這是庫存計劃的一部分,需要獲取庫存物品上次校準的日期。使用NSDateFormatter設置UIDatePicker日期

使用此代碼我收到的日期/時間字符串:

NSDate *choice = [pickedDate date]; 
calDate = [[NSString alloc] initWithFormat:@"%@", choice]; 

我結束了在calDate以下字符串:2011-11-11 21時56分38秒+0000

我試圖用下面的代碼來設置我的日期選擇器:

NSDate *date = [[[NSDate alloc] init] retain]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
NSLog(@"cal date = %[email protected]",drawingInfo.drawingDate); 
if([calDate length] != 0) { 
    date = [dateFormatter dateFromString:calDate]; 

    if(date != nil) { 
      [pickedDate setDate:date animated:NO]; 
    } 
} 

NSLog驗證字符串是否仍然有效。 如果我在if(date!= nil)上放置了一個斷點,它會向我顯示date = nil。

在此先感謝。

+0

pueden ayudarme CON estan pregunta http://stackoverflow.com/questions/15162835/how-to-use-nsdateformatter-to-venezuela gracias – tony 2013-03-01 17:24:19

回答

7

您錯過了日期格式中的Z格式說明符。

此代碼:

NSString *calDate = @"2011-11-11 21:56:38 +0000"; 
NSDate *date = [[[NSDate alloc] init] retain]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"]; 
//         right here ^

date = [dateFormatter dateFromString:calDate]; 

NSLog(@"date:%@", date); 

輸出:

2012-01-03 20:14:15.258 Craplet[38753:707] date:2011-11-11 21:56:38 +0000 

沒有Z:

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 

它輸出:

2012-01-03 20:16:10.456 Craplet[38885:707] date:(null) 

如果格式不匹配的日期字符串,則返回nil