Putting current time into label
Ii am trying to get date and time using date but when i run application it takes first time executed application time and date in short time is not changed.
NSDate *StrDate = [NSDate date];
NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init]开发者_JAVA技巧;
[Dateformat setDateFormat:@"DD-MM-YYYY"];
NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
[UserCntrl.timeDisplay setText:DateStr];
[Dateformat setDateFormat:@"HH:MM"];
NSMutableString *timeStr=[Dateformat stringFromDate:StrDate];
Place a scheduled timer in your uiview did show (or did load) 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 a second, updating your controller.
[NSDate date] makes a date object of the time you call it. You must call it again to update the date. In other words, you must do StrDate = [NSDate date]; whenever you want to get the current date in your method.
You have a bug in your code:
Instead of
[Dateformat setDateFormat:@"HH:MM"];
it should be
[Dateformat setTimeFormat:@"HH:MM"];
精彩评论