Paul Mastes
Paul Mastes

Reputation: 71

Using a NSTimer for HH:MM:SS?

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

Do I need to add code in .h or .m so I known which one?

At the moment it goes up like 1, 2, 3, 4 etc.

Just to let you known I'm bait of a amateur would you copy and past so I known what you mean.

.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];
}

Upvotes: 4

Views: 4773

Answers (1)

lawicko
lawicko

Reputation: 7344

First, declare baseDate variable in your FirstViewController.h, like this:

@interface FirstViewController : UIViewController {

    IBOutlet UILabel *time; 

    NSTimer *myticker;

    //declare baseDate
    NSDate* baseDate;
}

Then, in the FirstViewController.m start method add baseDate = [NSDate date] like this:

-(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];
}

Also note, that you will have to change the interval value for your timer, otherwise your label will only be updated once a second.

Upvotes: 7

Related Questions