Actually we want to compare the NSDate in this format "yyyy-MM-dd HH:mm", so how can we compare two date_time value for the date, hour and minute and ignore the second value in the objective c, ios ?
Asked
Active
Viewed 744 times
0
-
set the second values to `00` at both dates, and they won't mess the comparison up. – holex Apr 05 '16 at 15:59
-
You could use a `NSDateFormatter` to transforms those two `NSString` objects into `NSDate` objects, and then use `NSDateComponents` to check equality on the components that are relevant. Or, if they have really the same and easy format as you set (same timezone, etc.) you can just do a comparison on the substring (removing the last 2 characters that represent the minutes). – Larme Apr 05 '16 at 16:03
-
@Larme There are no strings, just to `NSDate`. The OP just wants to ignore the "seconds" of the two `NSDate` instances. – rmaddy Apr 05 '16 at 16:06
-
1On one hand, I'd like to close this question since it's essentially a duplicate of [Comparing two NSDate and ignoring the time component](http://stackoverflow.com/questions/1854890/comparing-two-nsdates-and-ignoring-the-time-component?rq=1). On the other hand, it might not be obvious to a newbie how to modify those answers to solve the problem of the current question. – DarkDust Apr 05 '16 at 16:07
-
@rmaddy: That's where the description of the question is tricky. The author uses `NSDate` terms, and a format too. Which is quite confusing, and since `NSDate` object `description` method show the +0000, that's why I made the assumption of `NSString` – Larme Apr 05 '16 at 16:08
2 Answers
4
Nowadays, probably the best way is to use -[NSCalendar isDate:equalToDate:toUnitGranularity:]
.
BOOL datesAreEqual = [[NSCalendar currentCalendar] isDate:date1
equalToDate:date2 toUnitGranularity:NSCalendarUnitMinute];
To compare them (find out which one is more recent/late), use -[NSCalendar compareDate:toDate:toUnitGranularity:]
instead.

DarkDust
- 90,870
- 19
- 190
- 224
0
NSCalendar
has a very handy method to compare dates constrained to a particular unit. Set the toUnitGranularity
parameter to NSCalendarUnitMinute
and the seconds are ignored.
NSDate *date1 = [NSDate date];
NSDate *date2 = [date1 dateByAddingTimeInterval:30.0];
NSComparisonResult compareDateIgnoringSeconds = [[NSCalendar currentCalendar]
compareDate:date1
toDate:date2
toUnitGranularity:NSCalendarUnitMinute];
NSLog(@"%@, %@, %ld", date1, date2, compareDateIgnoringSeconds);
The result is NSOrderedSame
for equality, NSOrderedAscending
and NSOrderedDescending
for date1
before date2
and date1
after date2

vadian
- 274,689
- 30
- 353
- 361