objective-c - 如何从 NSDate 倒计时并以小时和分钟显示

标签 objective-c ios nsdate nstimer

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

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

timer countdown label

这是我正在使用的代码。一个 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];
}

谢谢你的帮助

最佳答案

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

关于objective-c - 如何从 NSDate 倒计时并以小时和分钟显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13360442/

相关文章:

ios - 不会死的NS僵尸

ios - 将搜索字符串从 UISearchBar 转换为 MK MapView 地址

ios - 如何解决设备之间的 CloudKit 功能不一致

ios - 无法加载 bundle 中 Nib 引用的标识符为“com.techlitellc.vfd”的图像

objective-c - 从 Core Data 检索 NSDate 时的时区问题

objective-c - 从 Objective-C 调用 Swift 重载运算符

ios - UIButton 的 setFont 已弃用,我尝试了新方法但仍然失败

ios - 隐藏导航 Controller 后退按钮 iOS 7

IOS如何设置日期格式

ios - 比较两个NSDate的月份和日期