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



我想要一个从当前时间到特定日期的倒计时,并在标签中显示该值。我看了一些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中什么也没得到。

使用这个答案中的代码(为了示例的完整性,复制粘贴在下面(来获得倒计时周期的各个组件:

- (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];
}

声明成员变量,如NSDate*开始日期,*结束日期;无符号长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--;
}
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 中的做法

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

//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);
}

最新更新