【问题标题】:How to countdown from a NSDate and display it in hours and minutes如何从 NSDate 倒计时并以小时和分钟显示
【发布时间】:2012-11-13 12:04:41
【问题描述】:

我正在尝试从 NSDate 倒计时并以小时和分钟显示。像这样:1h:18min

目前我的日期正在更新为 UILabel 并倒计时,但显示如下:

这是我正在使用的代码。 startTimer 方法和 updateLabel 方法

 - (void)startTimer {
        // Set the date you want to count from

    // convert date string to date then set to a label
    NSDateFormatter *dateStringParser = [[NSDateFormatter alloc] init];
    [dateStringParser setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.000Z"];

    NSDate *date = [dateStringParser dateFromString:deadlineDate];

    NSDateFormatter *labelFormatter = [[NSDateFormatter alloc] init];
    [labelFormatter setDateFormat:@"HH-dd-MM-yyyy"];

    NSDate *countdownDate = [[NSDate alloc] init];

    countdownDate = date; 

    // Create a timer that fires every second repeatedly and save it in an ivar
    NSTimer *timer = [[NSTimer alloc] init];

    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];

}

- (void)updateLabel {

    // convert date string to date then set to a label
    NSDateFormatter *dateStringParser = [[NSDateFormatter alloc] init];
    [dateStringParser setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.000Z"];

    NSDate *date = [dateStringParser dateFromString:deadlineDate];

    NSDateFormatter *labelFormatter = [[NSDateFormatter alloc] init];
    [labelFormatter setDateFormat:@"HH-dd-MM"];


    NSTimeInterval timeInterval = [date timeIntervalSinceNow]; ///< Assuming this is in the future for now.


    self.deadlineLbl.text = [NSString stringWithFormat:@"%f", timeInterval];
}

感谢您的帮助

【问题讨论】:

    标签: objective-c ios nsdate nstimer


    【解决方案1】:
    - (NSString *)stringFromTimeInterval:(NSTimeInterval)interval 
      {
        NSInteger ti = (NSInteger)interval;
        NSInteger seconds = ti % 60;
        NSInteger minutes = (ti / 60) % 60;
        NSInteger hours = (ti / 3600);
        return [NSString stringWithFormat:@"%02i:%02i:%02i", hours, minutes, seconds];
      }
    

    【讨论】:

    • 谢谢!然后我将如何使用该方法将其应用于 self.deadlineLbl.text = [NSString stringWithFormat:@"%f", timeInterval];
    • 简单,创建另一个 NSString 并将这个 stringFromTimeInterval 的返回字符串传递给它,并打印那个 timeinterval2!
    【解决方案2】:

    由于您使用 NSTimeInterval ,您将获得时间间隔,即差异,以秒为单位,以小时和分钟显示它,您需要应用数学逻辑并转换它! 许多人需要几个循环才能做到这一点。

    试试这个

    问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 2014-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多