Using NSTimer for HH: MM: SS?

How can I change this code so that it has HH: MM: SS (hours, minutes, seconds,

And can you tell me if I need to add the code in .h or .m, so I knew which one

at the moment it rises like 1, 2, 3, 4, etc.

Hello guys, just so that you know that I am an amateur bait, you would copy and go so that I know what you mean thanks.

Yours faithfully

Floor

.h

@interface FirstViewController : UIViewController {

    IBOutlet UILabel *time; 

    NSTimer *myticker;

    //declare baseDate
    NSDate* baseDate; 

}

-(IBAction)stop;
-(IBAction)reset;

@end

.m

#import "FirstViewController.h"

@implementation FirstViewController

-(IBAction)start {
    [myticker invalidate];
    baseDate = [NSDate date];
    myticker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}

-(IBAction)stop;{ 

    [myticker invalidate];
    myticker = nil;
}
-(IBAction)reset;{

    time.text = @"00:00:00";
}
-(void)showActivity {
    NSTimeInterval interval = [baseDate timeIntervalSinceNow];
    NSUInteger seconds = ABS((int)interval);
    NSUInteger minutes = seconds/60;
    NSUInteger hours = minutes/60;
    time.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes%60, seconds%60];
}
+5
source share
1 answer

First declare a baseDate variable in your FirstViewController.h, for example:

@interface FirstViewController : UIViewController {

    IBOutlet UILabel *time; 

    NSTimer *myticker;

    //declare baseDate
    NSDate* baseDate;
}

Then, in the FirstViewController.m startup method, add baseDate = [NSDate date]as follows:

-(IBAction)start {
    [myticker invalidate];
    baseDate = [NSDate date];
    myticker = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}

After that, change your showActivity method to look like this:

-(void)showActivity {
    NSTimeInterval interval = [baseDate timeIntervalSinceNow];
    double intpart;
    double fractional = modf(interval, &intpart);
    NSUInteger hundredth = ABS((int)(fractional*100));
    NSUInteger seconds = ABS((int)interval);
    NSUInteger minutes = seconds/60;
    NSUInteger hours = minutes/60;
    time.text = [NSString stringWithFormat:@"%02d:%02d:%02d:%02d", hours, minutes%60, seconds%60, hundredth];
}

, , .

+7

All Articles