开发者

NSDate isEqualToDate: not working - does it look at seconds and split seconds?

I cannot understand why this method is not working. Does it look at the seconds and split seconds when using isEqualToDate:?

//Test that the NSDate category's DatePlusDays: method works
- (void)testNSDateCategoryDatePlusDays
{
    NSInteger numberOdDatesToAdd = 1;

    //Test method
    NSDate *result = [NSDate datePlusDays:numberOdDatesToAdd];

    //Correct result
    NSDate *now = [NSDate date];
    NSDate *correctResult = [now dateByAddingTimeInterval:60*60*24*numberOdDatesToAdd];

    NSLog(@"correct result: %@", correctResult);
    NSLog(@"result %@", result);
    STAssertTrue([correctResult isEqualToDate:result], @"Dates are not equal"); 

}

2011-04-19 09:29:02.939 [49535:207] correct result: 2011-04-20 08:29:02 +0000 2011-04-19 09:29:02.940 [49535:207] result开发者_如何学C 2011-04-20 08:29:02 +0000

+ (NSDate *)datePlusDays:(NSInteger)days
{
    NSDate *now = [NSDate date];
    return [now dateByAddingTimeInterval:60*60*24*days];
}


It compares down to the microsecond to see if the dates are exactly equal.

If you need less precision, use timeIntervalSinceDate: to test for the dates being within a range of microseconds, seconds, hours, days etc, of each other.


You could use something like this to only check on the date (ignoring the time):

- (BOOL)isDate:(NSDate*)date1 equalToDateIgnoringTime:(NSDate*)date2
{
    NSDateComponents *components1 = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date1];
    NSDateComponents *components2 = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date2];
    return ((components1.year == components2.year) &&
            (components1.month == components2.month) && 
            (components1.day == components2.day));
}


This code here will strip out the hours, minutes and seconds.

    //separate hours, min and seconds into their own integers
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:currentDate];
    NSInteger hour = [components hour];
    NSInteger minute = [components minute];
    NSInteger second = [components second];
    //subtract time of day from above nsdate object
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setHour:-hour];
    [comps setMinute:-minute];
    [comps setSecond:-second];
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:destinationDate  options:0];
    [comps release];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜