what I am trying to do is make a if statement with dates using greater than less than signs. For some reason only the greater than sign works. Here is my code:
create a NSDate object with the time 8:10 and one with 8:00. Now you can compare the given date with both these dates
if(([date0800 compare:date] == NSOrderingAscending) && [date0810 compare:date] == NSOrderingDescending) )
{
// date is between the other
}
to create the boundaries dates you can do this
NSDate *date = [NSDate date]; // now
NSDateComponents *components = [[NSCalendar currentCalendar] components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:date];
components.hour = 8;
components.minute = 0;
NSDate *date0800 = [[NSCalendar currentCalendar] dateFromComponents: components];
components.minute = 10;
NSDate *date0810 = [[NSCalendar currentCalendar] dateFromComponents: components];
if you insist of using operators like <
and >
, you can use the timeinterval of the date objects.
if(([date0800 timeIntervalSince1970] < [date timeIntervalSince1970]) && ([date0810 timeIntervalSince1970] > [date timeIntervalSince1970]))
{
// date lays between the other two
}
but beware of checking ==
on it, as it could be faulty due to rounding errors.
You can't use > or < to compare string objects. That actually compares pointers so we won't get into why > 'works' and < 'doesn't'.
For this kind of date comparison use NSDateComponents NSDateComponents Reference
NSString
objects are objects, and when you compare objects with C comparison operators (==, >, <, etc.) you are comparing their addresses, not their values. You need to use compare
, such as:
if ([dateString compare:@"0810"] == NSOrderedAscending &&
[dateString compare:@"0800"] == NSOrderedDescending) { ...
Though I'd recommend converting to NSDate
objects in most cases if you want to compare dates and times.
Here's the gist of a category I wrote on NSDate. I found it made my code more readable.
https://gist.github.com/nall/5341477
@interface NSDate(SZRelationalOperators)
-(BOOL)isLessThan:(NSDate*)theDate;
-(BOOL)isLessThanOrEqualTo:(NSDate*)theDate;
-(BOOL)isGreaterThan:(NSDate*)theDate;
-(BOOL)isGreaterThanOrEqualTo:(NSDate*)theDate;
@end
Here you are comparing string objects, with <
and >
, which does not do what you are expecting. You can use NSDateComponents
to get the hour and minute to compare those:
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components =
[gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit ) fromDate:today];
NSInteger hour = [weekdayComponents hour];
NSInteger minutes = [weekdayComponents minute];
BOOL homeroom = (hour == 8) && (minute < 10);
Or you can create a specific NSDate for 8:10 and 8:00 using NSDateFormater and using the compare:
function.