How can I perform two actions depending on the current time?
For example: Display labelA if current time is between 8am-2pm. Display labelB if current time is between 2pm-6pm.
Thanks!
How can I perform two actions depending on the current time?
For example: Display labelA if current time is between 8am-2pm. Display labelB if current time is between 2pm-6pm.
Thanks!
Why an IBAction
? Just do this:
- (void)viewDidLoad
{
[super viewDidLoad];
self.labelA.text = @"It's between 8am and 2pm";
self.labelB.text = @"It's between 2pm and 6pm";
NSDate *date = [NSDate date];
NSCalendar *gregorianCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComps = [gregorianCal components: (NSHourCalendarUnit | NSMinuteCalendarUnit)
fromDate: date];
if (dateComps.hour > 8 && dateComps.hour <= 14)
{
[self.view addSubview:self.labelA];
}
else if (dateComps.hour > 14 && dateComps.hour < 18)
{
[self.view addSubview:self.labelB];
}
}
Use NSDateComponents
to convert the current time (which you get from [NSDate date]
) into components like hour, minute, etc. Then just check the hour component to see what range it's in and do the appropriate label action based on that.