iOS 给定日期的倒计时器

标签 ios

我找到了this虽然它非常好。它似乎对我不起作用。

这是我对代码的修改:

-(void) updateCountdown
{
    
    NSString *dateString = @"2015-12-15 15:29:32";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dateFromString = [[NSDate alloc] init];
    // voila!
    dateFromString = [dateFormatter dateFromString:dateString];
    
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSLog(@"DATE: %@ %@",now, dateFromString);
    
    NSDateComponents *componentMint = [calendar components:NSMinuteCalendarUnit fromDate:now];
    
    self.lblMinitSetting.text=[NSString stringWithFormat:@"%02d",(60-componentMint.minute)];
    
}

时间正在更新,一切正常,只是它忽略了我指示的小时、分钟和秒标记。

即:

    NSString *dateString = @"2015-12-15 15:13:32";
    NSString *dateString = @"2015-12-15";

无论我使用上面两行中的哪一行,剩余时间都是相同的。

此外,我想同时获取小时、分钟和秒。

假设现在是下午 1 点,时间/日期显示当天下午 2:30。

我希望每小时的输出为1.5小时 我希望分钟的输出是90m 我希望秒数的输出为5400s 等等 不是 1小时30分0秒

感谢您的帮助

编辑:

这里的主要错误是倒计时发生在特定日期并忽略了时间。

我希望倒计时从现在开始到 future 的特定时间。

最佳答案

嘿,我已经在我的应用程序中完成了此操作,看看这是否对您有帮助

- (void)updateRemainingTimeFromDateString:(NSString *)strDate
                                forLabel:(UILabel *)label {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *newDate = [dateFormatter dateFromString:strDate];

    NSString *strRemTime = @"";

    int timeInterval = [newDate timeIntervalSinceDate:[NSDate date]];

    if (timeInterval != 0) {
        int noOfDays = timeInterval / (24 * 60 * 60);
        timeInterval = timeInterval % (24 * 60 * 60);
        int noOfHours = timeInterval / (60 * 60);
        timeInterval = timeInterval % (60 * 60);
        int noOfMinutes = timeInterval / 60;
        int noOfSeconds = timeInterval % 60;

        if (noOfDays != 0)
            strRemTime = [NSString stringWithFormat:@"%dD", noOfDays];

        if (strRemTime.length != 0)
            strRemTime = [NSString stringWithFormat:@"%@ %02dH", strRemTime, noOfHours];
        else
            strRemTime = [NSString stringWithFormat:@"%02dH", noOfHours];

        strRemTime = [NSString stringWithFormat:@"%@ %02dM %02dS", strRemTime, noOfMinutes, noOfSeconds];
    }
    [label setText:strRemTime];
}

抱歉,我没有按照您想要的方式对其进行格式化,但这仍然不难做到,日期将与当前日期进行比较,并且标签作为参数在此方法中传递,因此可以更新它使用 in 方法

关于iOS 给定日期的倒计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24114239/

相关文章:

ios - 从 iOS 应用上传到自己的 YouTube 帐户

ios - 查找字符串的范围

ios - 通用链接是否保留 POST 数据?

iOS 钥匙串(keychain) - kSecClassGenericPassword 和 kSecClassInternetPassword 之间有什么区别?

ios - UIButton 未在 swift 中调用操作函数

android - React Native 测试 404 网络图像

html - 在 iOS 上将 HTML 转换为 PDF 时出现问题

ios - 将对象添加到 JSONKit 创建的字典?

ios - 将 UIWebView 显示的 PDF 保存到本地

ios - 使用 UIAlertController 排除某些 View 的调光