无需考虑时间比较NSDates

时间:2013-11-02 16:55:00

标签: ios objective-c nsdate nsdatecomponents

基本上我有一天的提示功能,并提供与日期相关的特定提示,我需要一种方法来比较当前NSDate与提示的保存日期,无论时间如何。显然,1月1日的提示与上午10点和10点半有关,所以我无法比较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]])

1 个答案:

答案 0 :(得分:1)

根据经验,当您比较或操纵NSDate时,正确的工作工具通常是NSCalendarNSDateComponents的组合。

仅在需要格式化并显示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];
}