2011-01-19 90 views
1

我無法從字符串獲取今天的時間。我讀從一個的UITextField一時間,但日期出來的劃時代從字符串創建日期

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"HH-mm"]; 
[formatter setDateStyle:NSDateFormatterNoStyle]; 
[formatter setTimeStyle:NSDateFormatterShortStyle]; 
[formatter setLenient:YES]; 

NSLog(@"Format: %@",[formatter dateFormat]);  
NSDate *now = [formatter dateFromString:[textbox text]]; 
NSLog(@"Time from textfield: %@",now]); 

這給從日誌代碼以下日期的開始。

2011-01-19 18:56:28.193 MyApp[8284:207] The time for now: 1970-01-01 06:00:00 GMT 

回答

1

設置dateStyletimeStyle的格式將覆蓋您手動設置dateFormat。下面應該按預期工作:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"HH-mm"]; 
[formatter setLenient:YES]; 

NSLog(@"Format: %@",[formatter dateFormat]); 

[formatter release]; 

產生的日期對象將接近時代的開始,因爲你沒有提供的年,月,日。如果你想在文本框代表今天的日期時間的時候,你將不得不在一些額外的代碼添加:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"HH-mm"]; 
[formatter setLenient:YES]; 
NSDate *time = [formatter dateFromString:[textbox text]]; 
[formatter release]; 

NSCalendar *calendar = [NSCalendar currentCalendar]; 
NSDateComponents *comps = [calendar components:NSYearCalendarUnit | 
               NSMonthCalendarUnit | 
               NSDayCalendarUnit | 
               NSHourCalendarUnit | 
               NSMinuteCalendarUnit 
             fromDate:[NSDate date]]; 
NSDateComponents *timeComps = [calendar components:NSHourCalendarUnit | 
                NSMinuteCalendarUnit 
              fromDate:time]; 

[comps setHour:[timeComps hour]]; 
[comps setMinute:[timeComps minute]]; 
NSDate *date = [calendar dateFromComponents:comps]; 
NSLog(@"Date from textfield: %@",date); 
0
NSDate *todayDate = [NSDate date]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setTimeStyle:NSDateFormatterShortStyle]; 
NSString *currentTime = [dateFormatter stringFromDate:todayDate]; 
NSLog(@"The current time is:%@",currentTime); 
[dateFormatter release]; 
+2

我覺得OP是試圖將一個字符串文本字段轉換爲一個NSDate對象,您的解決方案將當前時間作爲字符串提供。 – 2011-01-19 19:10:56