以日/月/年格式显示特定日期的倒计时

时间:2011-12-04 20:11:48

标签: objective-c ios cocoa-touch nsdate countdown

在我的iPhone应用程序中,我希望UILabel计入某个特定日期。

到目前为止,我让用户从UIDatePicker中选择一个日期,但我无法弄清楚如何在逻辑上倒计时每个单位的日期。它也需要是实时的,所以你可以观察日期的变化,而不必重新加载视图,看看从现在开始到现在的差异。

我希望有这样的格式(稍后可能会更改,不确定): dd / mm / yyyy

1 个答案:

答案 0 :(得分:3)

每次要更新标签时,您都需要点击NSTimer,然后您需要使用NSDate的{​​{1}}方法来获取日期和日期之间的时间间隔现在。然后使用它来更新标签。

例如:

timeIntervalSinceNow

获取实际天数,月数,年数,小时数,分钟数和您还可以使用- (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]; } 秒,尤其是NSCalendar方法。看一下这个问题,进行更多讨论: Number of days between two NSDates