Search code examples
objective-cioscocoa-touchnsdatecountdown

Display a countdown to a particular date, in day/moth/year format


In my iPhone app I want to have a UILabel which counts down to a certain date.

So far I have the user select a date from a UIDatePicker, but I can't figure out how to actually logically countdown each unit of the date. It needs to be live as well, so you can watch the date change rather than having to reload the view and see the difference from now until then.

I want to have a format like so (might change it up later, not sure): dd / mm / yyyy


Solution

  • You will want an NSTimer to fire every time you wish to update the label and then you need to use NSDate's timeIntervalSinceNow method to get the time interval between your date and now. Then use that to update the label.

    For instance:

    - (void)startTimer {
        ...
        // Set the date you want to count from
        self.countdownDate = [NSDate date...]; ///< Get this however you need
    
        // Create a timer that fires every second repeatedly and save it in an ivar
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];
        ...
    }
    
    - (void)updateLabel {
        NSTimeInterval timeInterval = [self.countdownDate timeIntervalSinceNow]; ///< Assuming this is in the future for now.
    
        /**
         * Work out the number of days, months, years, hours, minutes, seconds from timeInterval.
         */
    
        self.countdownLabel.text = [NSString stringWithFormat:@"%@/%@/%@ %@:%@:%@", days, months, years, hours, minutes, seconds];
    }
    

    To get the actual number of days, months, years, hours, minutes & seconds you could also use NSCalendar and in particular the components:fromDate:toDate:options: method. Take a look at this question for some more discussion on that: Number of days between two NSDates