-2

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!

2 Answers2

1

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];
    }
}
michaelsnowden
  • 6,031
  • 2
  • 38
  • 83
0

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.

See: NSDate get year/month/day

Community
  • 1
  • 1
jsd
  • 7,673
  • 5
  • 27
  • 47