Getting the current time and updating it - Goal C

I know how to use NSDate to get the time and display it inside a UILabel.

I need to display date + hours and minutes. Any idea how I can update it without lively expectation?

Thanks!

+4
source share
4 answers

As your comments say, if you want changes in minutes to change the value of label.text

you need to do the following:

1st: get the current time:

 NSDate *date = [NSDate date]; NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *dateComponents = [calendar components:NSHourCalendarUnit fromDate:date]; 

and set label.text = CURRENTHOUR_AND_YOURMINNUTS ;

and then refresh the shortcut the next minute, for example:

first, you can check after 60 - nowSeconds [self performSelector: @selector (refreshLabel) withObject: nil afterDelay: (60 - dateComponents.minute)];

 - (void)refreshLabel { //refresh the label.text on the main thread dispatch_async(dispatch_get_main_queue(),^{ label.text = CURRENT_HOUR_AND_MINUTES; }); // check every 60s [self performSelector:@selector(refreshLabel) withObject:nil afterDelay:60]; } 

It will be checked every minute, therefore more effective the answers above.

When refreshLabel is called, it means the minutes are changed

+2
source

Use NSTimer to Update Time on Shortcut

 - (void)viewDidLoad { [super viewDidLoad]; [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES]; } -(void)updateTime { NSDate *date= [NSDate date]; NSDateFormatter *formatter1 = [[NSDateFormatter alloc]init]; //for hour and minute formatter1.dateFormat = @"hh:mm a";// use any format clockLabel.text = [formatter1 stringFromDate:date]; [formatter1 release]; } 
+5
source

You can use NSTimer to periodically get the current time.

 [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; - (void)timerFired:(NSTimer*)theTimer{ //you can update the UILabel here. } 
+1
source

You can use NSTimer, but given the methods above, UILabel will not update when Events are clicked, as the main thread will be busy tracking it. You need to add it to mainRunLOOP

  NSTimer* timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateLabelWithDate) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; -(void)updateLabelWithDate { //Update your Label } 

You can change the time interval (the speed at which you want to update).

-1
source

All Articles