程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> ios-從string中獲取NSDate

ios-從string中獲取NSDate

編輯:編程綜合問答
從string中獲取NSDate

有一個日期字符串,轉換成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.

不知道語法出什麼錯了呢?

最佳回答:


NSDate *date =  [[dateFormat dateFromString:dateStr] date];
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved