Entering the current time in a tag

I try to get the date and time using the date, but when I start the application, it takes the first time, the application’s runtime and date do not change in a short time.

NSDate *StrDate = [NSDate date]; NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init]; [Dateformat setDateFormat:@"DD-MM-YYYY"]; NSMutableString *DateStr = [Dateformat stringFromDate:StrDate]; [UserCntrl.timeDisplay setText:DateStr]; [Dateformat setDateFormat:@"HH:MM"]; NSMutableString *timeStr=[Dateformat stringFromDate:StrDate]; 
+4
source share
3 answers

Put the scheduled timer in your uiview to show (or load) the method:

 [NSTimer scheduledTimerWithTimeInterval:1.0f // 1 second target:self selector:@selector(updateTime:) userInfo:nil repeats:YES]; 

Then put this method in your view controller:

 - (void) updateTime:(id)sender { NSDate *StrDate = [NSDate date]; NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init]; [Dateformat setDateFormat:@"DD-MM-YYYY HH:mm:SS"]; NSMutableString *DateStr = [Dateformat stringFromDate:StrDate]; [UserCntrl.timeDisplay setText:DateStr]; // or whatever code updates your timer. I didn't check this for bugs. } 

This will call the updateTime method: once per second, updating your controller.

+4
source

[NSDate Date] makes the date object of the time you call it. You must call him again to update the date. In other words, you should do StrDate = [NSDate date]; when you want to get the current date in your method.

0
source

You have a bug in the code: Instead of [Dateformat setDateFormat:@"HH:MM"]; should be [Dateformat setTimeFormat:@"HH:MM"];

0
source

Source: https://habr.com/ru/post/1336029/


All Articles