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