2013-01-31 59 views
-1

我已經在文本文件中存儲了一個日期,我可以正確讀出它。該字符串的輸出是從NSString創建NSDate。

「6:00 PM」

就這樣。然而,當我這樣做:

//First, set the first datePicker 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 

    NSString *breakfastTimeStartLocation = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"breakfastTimeStart.txt"]; 

    NSString *time = [NSString stringWithContentsOfFile:breakfastTimeStartLocation encoding:NSUTF16StringEncoding error:nil]; 
    NSLog(@"Loaded time is %@", time); 
    NSDate *startDate = [dateFormatter dateFromString:time]; 

    NSLog(@"Start Date = %@", startDate); 

在此,time返回"6:00 PM",但startDate回報"(null)"

我必須失去了一些東西,爲什麼在世界上還沒有這樣的工作?

謝謝。

+0

另請注意,如果我只是想將datePicker設置爲'startDate',則會引發異常。 – Josiah

+1

您是否嘗試爲dateFormatter設置日期格式? [dateFormatter setDateFormat:@「MM/dd/YYYY」]; – Firo

+0

-1指責你的工具。 –

回答

-2

這並不是初始化一個NSDateFormatter以正確的方式,在指定的初始化是initWithDateFormat:allowNaturalLanguage:

這樣:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] 
initWithDateFormat:@"h:mm a" allowNaturalLanguage:NO]; 
+0

這是正確的方法。這在Cocoa Touch上甚至沒有。 :) – Josiah

+1

它必須得到一個格式,儘管...使用'setTimeFormat:'和'setDateFormat:' – iluvcapra

+0

這是不正確的。根據NSDateFormatter文檔,除非您需要預先安裝OS X Tiger行爲,否則請使用'init'。 –

1

我認爲,問題是,你永遠不會設置一個日期格式。即使這不是唯一的問題,它可能是一個。嘗試類似:

[dateFormatter setDateFormat:@"MM/dd/YYYY"];