2013-02-26 261 views
2

我有一個日期字符串,我試圖轉換成NSDate比較它與當前dateTime。我試圖實現這一點,但創建一個空值爲IM即將嘗試轉換的日期。從字符串獲取NSDate

這是我試過的。

-(BOOL)checkTime{ 

    //create an instance of the database oject 
    DataBase * dataBase = [[DataBase alloc] init]; 

    //get the times 
    NSMutableArray *times = [dataBase allDataFrom:@"timings"]; 

    //set date time to string and refresh time to float. 
    NSString *dateStr = times[1]; 
    float refreshTime = [times[2] floatValue]; 


    // Convert string to date object 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
    NSDate *date = [dateFormat dateFromString:dateStr]; 

    //get the time now 
    NSDate* timeNow = [NSDate date]; 

    NSLog(@"dateStr: %@",dateStr); 
    NSLog(@"DataBase Date: %@",date); 
    NSLog(@"Current Date: %@",timeNow); 
    NSLog(@"Time until refresh. (seconds): %f", refreshTime); 

    // If date is greater than refresh then update the data 
    if ([timeNow timeIntervalSinceDate:date] > refreshTime) 
    { 
     NSLog(@"Data Needs to be checked."); 
     return YES; 

    }else{ 
     NSLog(@"Data is fresh."); 

     return NO; 

    } 


} 

這是林從記錄我的所有值

dateStr: 2013/02/26 12:39:28 
DataBase Date: (null) 
Current Date: 2013-02-26 12:57:49 +0000 
Time until refresh. (seconds): 30.000000 
Data is fresh. 

讓我有語法不正確或莫不是別的東西,我錯過了什麼?

+0

顯示的'times'數組中的值? – graver 2013-02-26 14:08:54

+1

你見過這個有用的鏈接http://www.ios-developer.net/iphone-ipad-programmer/development/date-and-time/date-and-time-examples – topcat3 2013-02-26 14:09:58

回答

3

您輸入的日期和格式不匹配!

格式:

yyyy-MM-dd HH:mm:ss 

輸入:

2013/02/26 12:39:28 

(斜槓,而不是連字符和一個額外的空間)。

+0

謝謝你就是這樣。感覺愚蠢我現在錯過了它:P – Will 2013-02-26 14:13:19

2

當你的驗證碼NSLog(@"dateStr: %@",dateStr);打印dateStr: 2013/02/26 12:39:28

而且要設置您的日期格式爲[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 這就是爲什麼你越來越NSLog(@"DataBase Date: %@",date);數據庫日期:(空)`。

你需要做的是:

[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
+0

謝謝你就是這樣。感覺很傻,我現在錯過了:P – Will 2013-02-26 14:14:37