Putting current time into label

前端 未结 3 509
面向向阳花
面向向阳花 2021-01-03 07:44

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.

         


        
相关标签:
3条回答
  • 2021-01-03 08:23

    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.

    0 讨论(0)
  • 2021-01-03 08:24

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

    0 讨论(0)
  • 2021-01-03 08:32

    [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.

    0 讨论(0)
提交回复
热议问题