【问题标题】:NSDate countdown from NOW to NSDateNSDate 从现在到 NSDate 倒计时
【发布时间】:2013-01-18 19:15:59
【问题描述】:

如何以 HH:mm:ss 格式显示从现在到将来会发生的所需 NSDate 的倒计时?

【问题讨论】:

    标签: objective-c nsdate countdown


    【解决方案1】:

    documentation开始。

    NSDate *future = // whatever
    
    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
    
    - (void)updateCounter:(NSTimer *)tmr
    {
        NSTimeInterval iv = [future timeIntervalSinceNow];
        int h = iv / 3600;
        int m = (iv - h * 3600) / 60;
        int s = iv - h * 3600 - m * 60;
        aUILabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", h, m, s];
        if (h + m + s <= 0) {
            [tmr invalidate];
        }
    }
    

    【讨论】:

      【解决方案2】:

      您必须使用计时器来标记日期。

      存储未来日期,并继续减去未来日期 - [nsdate today]...

      以秒为单位计算时间,并将其计算为小时、分钟、秒...

      //制作两个属性NSDate *nowDate, *futureDate

      futureDate=...;
      
      nowDate=[NSDate date];
      
      long elapsedSeconds=[nowDate timeIntervalSinceDate:futureDate];
      NSLog(@"Elaped seconds:%ld seconds",elapsedSeconds);
      
      NSInteger seconds = elapsedSeconds % 60;
      NSInteger minutes = (elapsedSeconds / 60) % 60;
      NSInteger hours = elapsedSeconds / (60 * 60);
      NSString *result= [NSString stringWithFormat:@"%02ld:%02ld:%02ld", hours, minutes, seconds];
      

      这对你来说很方便...kindly check the project...

      【讨论】:

      • 嗯..这个结果返回:-114384:00:-24(数字也在上升!)
      • 这就是我获取未来日期的方式: NSString *dateStr = @"15:21:00"; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [日期格式 setDateFormat:@"HH:mm:ss"]; NSDate *date = [dateFormat dateFromString:dateStr];
      • oooppppssss...[futureDate timeIntervalSinceDate:nowDate] 反转条件..交换futureDate & nowDate..
      • 为什么你只需要小时,分钟,秒......如果你有约会,那么抽吸会更容易......
      • 那我会使用什么完整的日期格式?我的意思是,除了 HH:mm:ss 之外,我还包括什么以获得完整的“日期”
      【解决方案3】:

      试一下这段代码:

      NSTimer* timer= [NSTimer scheduledTimerWithInterval: [self.futureDate timeIntervalSinceNow] target: self selector: @selector(countdown:) userInfo: nil, repeats: YES];
      

      倒计时:方法:

      - (void) countdown: (NSTimer*) timer
      {
          if( [self.futureDate timeIntervalSinceNow] <= 0)
          {
              [timer invalidate];
              return;
          }
          NSDateComponents* comp= [ [NSCalendar currentCalendar] components: NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit startingDate: [NSDate date] toDate: self.futureDate options: 0];
          NSLog(@"%lu:%lu:%lu", comp.hour,comp.minute.comp.second);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-26
        • 1970-01-01
        • 1970-01-01
        • 2013-11-24
        • 1970-01-01
        相关资源
        最近更新 更多