0

I am trying to get a timer to start from 00:00:00 (minutes:seconds:milliseconds) and count up. I found this and this but I can't get it to quite work, it displays the current time and date.

My code is as follows:

- (void)timerTicked:(NSTimer *)timer
{
    NSDate *date = [NSDate date];
    unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* components = [calendar components:flags fromDate:date];
    NSDate* dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];

    static NSDateFormatter *dateFormatter;
    if (!dateFormatter) {
        dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"mm:ss:SS";
    }

    self.timerLabel.text = [dateFormatter stringFromDate:dateOnly];
}
Community
  • 1
  • 1
  • 3
    That code has nothing to do with what you want to do. Think about what you need to do: Store a start date reference, then on every tick of the timer subtract the current time from the start time and show that (You can reuse portions of the code above) – borrrden Jan 29 '14 at 00:56

1 Answers1

0

Here's a detailed outline of what to do:

Create an instance variable of type NSDate that you will use to record the start time. Let's call that variable startTime;

Write a startTimer method that:

  • Save the current time to startTime.
  • Starts a timer that fires every second, or whatever update interval you want. It can call your timerTicked method.

In your timerTicked method, save the current date in a local variable "now".

Use the NSCalendar method components:fromDate:toDate:options: to calculate the number of minutes and seconds since the timer started.

For milliseconds, you'll probably have to do your own calculation, something like this:

NSTimeInterval elapsedSeconds = [now timeIntervalSinceDate: startTime];
milliseconds = floor(1000*(elapsedSeconds-floor(elapsedSeconds)));
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • 1
    There is no need to deal with `NSCalendar and components. You can safely calculate the minutes, seconds, and milliseconds from the `elapsedSeconds` value. – rmaddy Jan 29 '14 at 01:59
  • 1
    Yup, true enough. I started out outlining it that way, and then figured I should use the OPs NSCalendar based approach – Duncan C Jan 29 '14 at 02:27