iOS:倒数计时器的dateformatter

时间:2014-06-05 11:45:15

标签: ios objective-c timer

我正在尝试在iOS中实现倒数计时器,即在通过未来的特定日期时,应显示计时器,例如从当前日期开始2 days, 4 hours, 17 minutes remaining

为此,我使用以下代码:

viewDidLoad中的

// 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?
    NSDateFormatter *df = [[NSDateFormatter alloc] init];

    [df setDateFormat:@"MM/dd/yyyy hh:mm:ss"];

    NSDate *targetDate = [NSDate date];

    NSString *strDate = [[self campaignDetail] objectForKey:@"expire_date"];
    NSLog(@"%@", strDate); // 06/06/2014 19:00:00
    targetDate = [df dateFromString: strDate];
// targetDate comes as nil when I NSLog this. I think this is causing the problem

    if ([targetDate earlierDate:now] == targetDate) {
        [theTimer invalidate];
    } else {
        NSUInteger flags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
        NSDateComponents *components = [[NSCalendar currentCalendar] components:flags fromDate:now toDate:targetDate options:0];
//        [self.labelTime_left setText:[NSString stringWithFormat:@"%d hours, %d minutes and %d seconds remaining", [components hour], [components minute], [components second]]];
        NSLog(@"there are %d hours, %d minutes and %d seconds remaining", [components hour], [components minute], [components second]);
    }
}

计时器方法被触发,但是当我调试和NSLog targetDate时,我得到它为零。请参阅上面的代码,看看我把它作为零。

我哪里出错了?我该如何解决这个问题?

0 个答案:

没有答案