Search code examples
iosnstimeruidatepickercountdown

UIDatePicker, NSTimer, & Formatting the date...?


I have a UIDatePicker and a UILabel to display the chosen date. Right now, the date is displayed as '2013-8-30 10:30:54 +0000'. I would like the date to instead be displayed as '00:00:00:00' in the order 'dd:hh:mm:ss. Then I would like to initiate a timer from an IBAction that begins counting down from the chosen date in the display for 'dd:hh:mm:ss'. any help or reference code that I could analyze would be greatly appreciated. I'm new and completely self taught. Thanks in advance. Cheers!

@synthesize picker;
@synthesize label;

-(IBAction)displayDate:(id)sender {
    NSDate *selected = [picker date];
    NSString *date = [selected description];
    self.label.text = date;
}

- (void)viewDidLoad {
    NSDate *now = [NSDate date];
    [picker setDate:now animated:YES];
    self.label.text = [now description];
}
@end

Solution

  • First:

    To display the date in the format you want, just use NSDateFormatter, like in the example below:

    self.formatter = [NSDateFormatter new]; //save a property of NSDateFormatter type, you'll use this before
    [formatter setDateFormat:@"dd:HH:mm:ss"];
    
    self.date = [NSDate date]; //save in a property, this will be your start date
    self.label.text = [formatter stringFromDate:self.date];
    

    Second:

    To perform a countdown-like behaviour, you can deduct one second (or more, depending what you want) from your date, transform the new date in string again and update your label. Here's how you would do that :

    Setup a NSTimer somewhere:

    [NSTimer scheduledTimerWithTimeInterval:1.0
                                     target:self
                                   selector:@selector(refreshLabel)
                                   userInfo:nil
                                    repeats:YES];
    

    And implement the method refreshLabel:

    -(void)refreshLabel
    {
        NSDate *dateCountDown = [NSDate dateWithTimeIntervalSince1970:[self.date timeIntervalSince1970] - 1]; //the start-up date minus 1 sec.
        self.label.text = [formatter stringFromDate:dateCountDown];
        self.date = dateCountDown;
    }