18

这段代码有什么问题?

NSDate *matchDateCD = [[object valueForKey:@"matchDate"] description]; // from coredata NSDate
NSDate *add90Min = [matchDateCD dateByAddingTimeInterval:5400];



if ( matchDateCD >=[NSDate date] || add90Min <= matchDateCD )
{

    cell.imageView.image = [UIImage imageNamed: @"r.gif"];//Show image in the table

}    

如果比赛正在进行或持续 90 分钟,我需要在表格中显示此图像

4

5 回答 5

41

我不知道object你调用valueForKey:的是什么,但假设它返回一个NSDate对象,你的额外调用description会将一个NSString(描述的返回值)分配给matchDateCD. 那不是你想做的。

这就是你想要做的:

NSDate *matchDateCD = [object valueForKey:@"matchDate"];
NSDate *add90Min = [matchDateCD dateByAddingTimeInterval:(90*60)]; // compiler will precompute this to be 5400, but indicating the breakdown is clearer

if ( [matchDateCD earlierDate:[NSDate date]] != matchDateCD ||
     [add90Min laterDate:matchDateCD] == add90Min )
{
    cell.imageView.image = [UIImage imageNamed: @"r.gif"];//Show image in the table
}
于 2012-06-13T19:37:38.900 回答
10

使用 NSDate 的 dateByAddingTimeInterval 方法将秒数添加到时间。

NSDate* newDate = [oldDate dateByAddingTimeInterval:90];

然后,您可以使用 NSDateFormatter 或 NSDateComponents 重新获取新的时间。

于 2012-06-13T17:06:16.380 回答
5

您还可以设置小时、年、月和秒等

     NSDateComponents *components= [[NSDateComponents alloc] init];
    [components setMinute:30];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *myNewDate=[calendar dateByAddingComponents:components toDate:[NSDate date] options:0];
于 2015-04-09T15:01:43.877 回答
3

对于斯威夫特 4

要将 90 分钟添加到日期,请使用addTimeInterval(_:)

let now = Date()
let minutes: Double = 90
let add90MinsDate = now.addingTimeInterval(minutes * 60)

对于问题,下面的快速代码

if let matchDateCD: Date = objest.value(forKey: "matchDate") as? Date {
   let add90Min = matchDateCD.addingTimeInterval(90 * 60)
   if matchDateCD >= Date() || add90Min > matchDateCD {
        cell.imageView.image = UIImage(named: "r.gif")
   }
}
于 2017-11-26T20:23:28.427 回答
1

日期是对象,所以比较指针不好。将它们转换为常见的时间间隔(浮点数):

NSDate *now = [NSDate date];
NSDate *tenMinsLater = [now dateByAddingTimeInterval:600];

NSTimeInterval nowInterval = [now timeIntervalSinceReferenceDate];
NSTimeInterval *tenMinsLaterInterval = [tenMinsLater timeIntervalSinceReferenceDate];

if (nowInterval > tenMinsLaterInterval) NSLog(@"never get here");

或者,使用比较器:

// also false under newtonian conditions
if (now > [now laterDate:tenMinsLater]) NSLog(@"einstein was right!");

或使用 earlyDate: 或比较:

于 2012-06-13T17:17:49.283 回答