2

本质上,我有一个每日提示功能,其中包含与日期相关的特定提示,并且我需要一种方法来比较当前NSDate与保存​​的提示日期,而不考虑时间。显然,1 月 1 日的提示与上午 10 点和 10:30 相关,所以我无法从字面上比较NSDates. 以下是我尝试过的一些事情:

尝试 1 - 不起作用

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];

NSDateFormatter *df = [[NSDateFormatter alloc] init];
//    [df setDateFormat:@"yyyy-MM-dd hh:mm:ss a"];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];

尝试 2 - 不起作用

NSString * zoneString = [[NSString stringWithFormat:@"%i-%i-%iT00:00:00", year, month, day] substringFromIndex:([[NSString stringWithFormat:@"%i-%i-%iT00:00:00", year, month, day] length] - 5)];
NSTimeInterval timeInterval = [[zoneString substringToIndex:3] intValue] * 3600;
timeInterval += [[zoneString substringFromIndex:3] intValue] * 60;

NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:timeInterval]];
[formatter setDateFormat:@"yyyy'-'MM'-'dd' 'HH':'mm':'ss ZZZ"];
NSLog(@"%@", [formatter stringFromDate:myDate]);

尝试 3 - 不起作用

NSDate *date = [NSDate date];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&date interval:NULL forDate:date];

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

if ([[dateFormat stringFromDate:date] isEqualToString:[dateFormat stringFromDate:tipDate]])
4

1 回答 1

1

根据经验,当您比较或操作NSDates 时,适合该工作的工具通常是NSCalendar和的组合NSDateComponents

仅在NSDateFormatter需要格式化和显示NSDate.

考虑到这一点,这NSDateComponents是要走的路,因为您想比较两个日期的组件子集。

创建两个NSDateComponents实例并比较它们。

例子:

- (BOOL)isToday:(NSDate *)date {
    NSDateComponents *todayComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
                                                                        fromDate:[NSDate date]];
    NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
                                                                       fromDate:date];
    return [dateComponents isEqual:todayComponents];
}
于 2013-11-02T17:02:26.693 回答