Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing the time of two NSDates, ignoring the date component

I want to compare two NSDates with NOW ([NSDate date]).

NSDate *date1 = [NSDate dateWithString:@"1982-02-12 07:00:00 +0100"];
NSDate *now   = [NSDate dateWithString:@"2012-01-25 10:19:00 +0100"]; //example
NSDate *date2 = [NSDate dateWithString:@"1989-02-12 15:00:00 +0100"];

I would like to check if now is between date1 and date2. In the example above this is the case. The date component should be completely ignored, so only the time component should be compared. How could I accomplish this?

Thanks in advance!

like image 526
Rens Avatar asked Jan 25 '12 09:01

Rens


2 Answers

unsigned int flags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSCalendar* calendar = [NSCalendar currentCalendar];

NSDateComponents* components = [calendar components:flags fromDate:date1];

NSDate* timeOnly = [calendar dateFromComponents:components];

This will give you a date object where everything but the hours/minutes/seconds have been reset to some common value. Then you can use the standard NSDate compare functions on them.

For reference, here is the opposite question to yours: Comparing two NSDates and ignoring the time component

like image 191
UIAdam Avatar answered Nov 15 '22 23:11

UIAdam


You can create a date representing the start of today and add the time as components to it to get the boundary dates.

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


NSDateComponents *startComps = [[NSDateComponents alloc] init];
startComps.hour = 7;
startComps.minute = 30;

NSDateComponents *endComps = [[NSDateComponents alloc] init];
endComps.hour = 20;

NSDate *startDate =  [[NSCalendar currentCalendar] dateByAddingComponents:startComps toDate:startOfToday options:0];
NSDate *endDate =  [[NSCalendar currentCalendar] dateByAddingComponents:endComps toDate:startOfToday options:0];

if ([startDate timeIntervalSince1970] < [now timeIntervalSince1970] && [now timeIntervalSince1970]  < [endDate timeIntervalSince1970]) {
    NSLog(@"good");
}
like image 24
vikingosegundo Avatar answered Nov 15 '22 23:11

vikingosegundo