Compare current time with fixed time 05:00:00 PM

How to compare the current time [NSDate date] with the fixed time 05:00:00 PM.

That 05:00 PM has already passed or not. I just need a BOOL check for this.

+3
source share
4 answers
- (BOOL)past5pm
{
    NSCalendar *gregorianCalender = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *components = [gregorianCalender components:NSHourCalendarUnit fromDate:[NSDate date]];

    if([components hour] >= 17) // NSDateComponents uses the 24 hours format in which 17 is 5pm
       return YES;

    return NO;
}
+3
source
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]  autorelease];
[dateFormatter setDateFormat:@"HH.mm"];
NSDate *currentDate = [NSDate date];
NSString *curDate = [dateFormatter stringFromDate:currentDate];

if ([curDate doubleValue] >= 17.00) 
{
    //set your bool
}
+1
source

try it

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setDateFormat:@"hh:mm:ss a"];

        NSDate* date = [NSDate date];

        //Get the string date
        NSString* str = [dateFormatter stringFromDate:date];

        NSDate *firstDate = [dateFormatter dateFromString:@"05:00:00 PM"];

        NSDate *secondDate = [dateFormatter dateFromString:str];

        NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];

        NSLog(@"Time Diff - %f",timeDifference);
0
source

You can probably use a simple C-style code and get the difference as an integer, and then decide what you need to return from the comparison function, depending on whether the difference is positive or negative. You can also compare minutes this way. Remember to import time.h.

    time_t now = time(NULL);
    struct tm oldCTime;
    localtime_r(&now, &oldCTime);
    int hours = oldCTime.tm_hour;
    int diff = 17-hours;
    NSLog(@"Time difference is: %d.", diff);
0
source