如何从当前日期倒计时到特定的NSDate?

时间:2013-05-20 08:16:17

标签: ios label nsdate countdown

我希望从当前时间到特定日期倒计时,并在标签中显示该值。我查看了一些NSTimer教程,但我无法弄清楚如何将它们应用到我的情况中。

NSTimeInterval TimeInterval = [aString doubleValue]; 
NSDate* upperDate = [aDate dateByAddingTimeInterval:TimeInterval];
NSDate* Today = [NSDate date];

//cell.myLabel.text = here i should write a countdown.

抱歉代码不足。我经常尝试写一些自己的代码,然后在这里提问,但这次我无法想出要写的内容。

修改 所以有了PartiallyFinite的答案,我想到了我如何设置计时器。但因为我使用tableview,我无法实现MyTimerLabel的重复消息。这就是我刚刚做的:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MyCell";
    MekanListesiViewCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }


    aClass *aC = [myArray objectAtIndex:indexPath.row];
    NSTimeInterval TimeInterval = [aC.aTimeIntervalwithString doubleValue];
    NSDate* UpperDate = [aC.aNSDate dateByAddingTimeInterval:TimeInterval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:[NSDate date] toDate:UpperDate options:0];
    NSInteger days     = [dateComponents day];
    NSInteger months   = [dateComponents month];
    NSInteger years    = [dateComponents year];
    NSInteger hours    = [dateComponents hour];
    NSInteger minutes  = [dateComponents minute];
    NSInteger seconds  = [dateComponents second];
    NSString *countdownText = [NSString stringWithFormat:@"%d Days %d:%d:%d", days, hours, minutes, seconds];
    cell.countdownText= countdownText;
    [self performSelector:@selector(updateCoundown)]; // The delay is in seconds, make it whatever you want.


    return cell;
}
At myCellView.h
@interface MekanListesiViewCell : UITableViewCell
@property (nonatomic, weak) IBOutlet UILabel *MyTimerLabel;
@property(weak)NSString *countdownText;
at myCellView.m

-(void)updateCoundown{

       MyTimerLabel.text = countdownText;
    [self performSelector:@selector(updateCoundown) withObject:nil afterDelay:1];
}

我在MyTimerLabel中什么也没得到。

4 个答案:

答案 0 :(得分:17)

使用this answer中的代码(下面复制粘贴以获得示例的完整性)来获取倒计时期间的各个组成部分:

- (void)updateCountdown {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSDate *startingDate = [dateFormatter dateFromString:@"2005-01-01"];
    NSDate *endingDate = [NSDate date];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0];

    NSInteger days     = [dateComponents day];
    NSInteger months   = [dateComponents month];
    NSInteger years    = [dateComponents year];
    NSInteger hours    = [dateComponents hour];
    NSInteger minutes  = [dateComponents minute];
    NSInteger seconds  = [dateComponents second];

然后我们可以创建一个包含所有这些数字的字符串:

    NSString *countdownText = [NSString stringWithFormat:@"%d Years %d Months %d Days %d Hours %d Minutes %d Seconds", days, months, years, hours, minutes, seconds];
    cell.myLabel.text = countdownText;

然后,我们可以使用performSelector:withObject:afterDelay:在指定的延迟后再次调用此方法(请注意延迟以秒为单位):

    [self performSelector:@selector(updateCountdown) withObject:nil afterDelay:1];
}

答案 1 :(得分:2)

声明成员变量之类的 NSDate * startDate,* EndDate; unsigned long countDownSeconds;

根据您的要求

-(void)setUpCountDown{
    startDate = [NSDate date]; //Current time
    NSDate *endDate = [startDate dateByAddingTimeInterval:10000]; //some future date
    NSTimeInterval milliseconds = [endDate timeIntervalSinceDate:startDate];/////will give time in milliseconds
    countDownSeconds = (unsigned long)milliseconds/1000;
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown:) userInfo:nil repeats:YES];
}

-(void)countDown:(NSTimer *)timer{
    if (countDownSeconds<=0) {
        [timer invalidate];
        timer = nil;
    }
    NSLog(@"Time Elapsed in seconds %d", countDownSeconds);
    countDownSeconds--;
}

答案 2 :(得分:1)

let formatter = NSDateFormatter()
let userCalendar = NSCalendar.currentCalendar()
let requestedComponent: NSCalendarUnit = [
    //NSCalendarUnit.Month,
    //NSCalendarUnit.Day,
    NSCalendarUnit.Hour,
    NSCalendarUnit.Minute,
    NSCalendarUnit.Second

]
func printTime() {
    formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
    let startTime = NSDate()
    let endTime = formatter.dateFromString("12/25/16 8:00:00 a")
    let timeDifference = userCalendar.components(requestedComponent, fromDate: startTime, toDate: endTime!, options: [])
    self.TimeLabel.text = " \(timeDifference.hour)Hours \(timeDifference.minute)Minutes \(timeDifference.second) Seconds"
}

//Put this in your initialiser

let timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(myProject.printTime), userInfo: nil, repeats: true)
    timer.fire()

我知道这个帖子很老,但这就是我在Swift中的表现方式

答案 3 :(得分:0)

保留一个实例变量来保存日期

//Fire Timer
_savedDate = [[NSDate date]dateByAddingTimeInterval:30];
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(countDown:) userInfo:nil repeats:YES];

- (void)countDown:(NSTimer *)timer
{
    NSDate *date = [NSDate date];

    if ([date isEqualToDate:_savedDate]) {
        [timer invalidate];
    }

    NSDateComponents *dateComponents = [[NSCalendar currentCalendar]components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:date toDate:_savedDate options:0];
    NSLog(@"%02d:%02d:%02d",dateComponents.hour,dateComponents.minute,dateComponents.second);
}