Alex Rivera | Logout

Comparing the time of two NSDates, ignoring the date component

Asked 2012-01-25T09:22:52.420
13

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!

Edit
Report

1 Answer

28
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

answered 2012-01-25T09:28:10.043

Your Answer