2 bluetooth99 bluetooth99 于 2013.02.27 10:07 提问

从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.

不知道语法出什么错了呢?

1个回答

zzzili
zzzili   2013.02.27 11:54
已采纳
NSDate *date =  [[dateFormat dateFromString:dateStr] date];
Csdn user default icon
上传中...
上传图片
插入图片