如何确定NSDate是否为今天

时间:2015-04-08 00:31:36

标签: objective-c xcode

我是一名经验丰富的Unix C程序员,对于Objective C和OS X来说相对较新。我想确定今天是否有NSDate。我的方法是从一个好的解决方案here复制而来的:

    + (BOOL)        isToday:(NSDate *)aDate {
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:[NSDate date]];
    NSDate *today = [cal dateFromComponents:components];
    components = [cal components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:aDate];
    NSDate *otherDate = [cal dateFromComponents:components];

    BOOL isToday = [today isEqualToDate:otherDate];
    return isToday;
}

代码编译,但为每个NSInteger NSxxxCalendarUnit生成了弃用警告。快速搜索显示NSCalendarUnixxxx形式的更新常量。

如何使用新常量?我尝试更换线路:

components = [cal components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:aDate];

使用

components = [cal component:(NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:aDate];

但我收到转换警告。我是否需要明确地将此OR持续转换?新常量的类型为NSUInteger,NSCalendarUnit。 "组件:"争论似乎是期待NSCalendarUnit,所以我不确定我错过了什么...

而且,是的,我知道iOS8和OS X 10.10包含新的日历功能(描述为here),例如isDateInToday:,但我正在寻找兼容iOS 7的解决方案。

1 个答案:

答案 0 :(得分:2)

问题是您已将components:参数的名称写为component:。那些不是一回事,你应该知道你是否是一位经验丰富的C程序员" - 正如名为thingthings的两个变量不同。

如果您更正了该错误,那么您对组件名称进行现代化的更改将编译得很好,没有任何警告:

+ (BOOL) isToday:(NSDate *)aDate {
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:(NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:[NSDate date]];
    NSDate *today = [cal dateFromComponents:components];
    components = [cal components:(NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:aDate];
    NSDate *otherDate = [cal dateFromComponents:components];
    BOOL isToday = [today isEqualToDate:otherDate];
    return isToday;
}