iOS Countdown Timer To Specific Date

三世轮回 提交于 2019-12-03 21:40:49
danh

The way to count down to a particular date is to just start a timer and ask each time it fires whether that date has come to pass. The second problem is how to calculate the hours minutes seconds until that time for the UI. The answer there is NSDateFormatter -- definitely not *60 or *24 math.

@property (strong, nonatomic) NSDate *targetDate;

// compute targetDate as you have it

// ...
self.targetDate = [formatter dateFromString:str]

// start a timer
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES]; 

- (void)updateCounter:(NSTimer *)theTimer {

    NSDate *now = [NSDate date]; 
    // has the target time passed?
    if ([self.targetDate earlierDate:now] == self.targetDate) {
        [theTimer invalidate];
    } else {
        NSUInteger flags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
        NSDateComponents *components = [[NSCalendar currentCalendar] components:flags fromDate:now toDate:self.targetDate options:0];

        NSLog(@"there are %ld hours, %ld minutes and %ld seconds remaining", (long)[components hour], (long)[components minute], (long)[components second]);
    }
}

Logic error....

-(void) viewWillAppear:(BOOL)animated {

    NSString *str =@"12/27/2013";
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"MM/dd/yyyy"];
    NSDate *date = [formatter dateFromString:str];

    NSTimeInterval numberOfSecondsUntilSelectedDate = [date timeIntervalSinceNow];
    NSInteger numberOfDays = numberOfSecondsUntilSelectedDate / 86400;


    startTime = [[NSDate date] retain];

    secondsLeft = numberOfSecondsUntilSelectedDate;
    NSLog(@"number%f", numberOfSecondsUntilSelectedDate);
    [self countdownTimer];

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!