iOS开发:计算剩余时间 - 剩余天数、小时和分钟 - Objective-C代码示例
"// 获取当前时间\nNSDate *currentDate = [NSDate date];\n\n// 设置目标时间\nNSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];\n[dateFormatter setDateFormat:"yyyy-MM-dd HH:mm:ss"];\nNSDate *targetDate = [dateFormatter dateFromString:"2022-12-31 23:59:59"];\n\n// 计算剩余时间\nNSTimeInterval timeInterval = [targetDate timeIntervalSinceDate:currentDate];\nNSInteger remainingSeconds = (NSInteger)timeInterval;\n\n// 计算天、小时和分钟\nNSInteger days = remainingSeconds / (60 * 60 * 24);\nNSInteger hours = (remainingSeconds / (60 * 60)) % 24;\nNSInteger minutes = (remainingSeconds / 60) % 60;\n\n// 输出剩余时间\nNSLog(@"剩余时间:%ld天 %ld小时 %ld分钟", (long)days, (long)hours, (long)minutes);\n"在这个示例中,我们首先使用[NSDate date]获取当前时间,然后使用NSDateFormatter将给定的目标时间字符串转换为NSDate对象。接下来,我们使用[targetDate timeIntervalSinceDate:currentDate]计算当前时间与目标时间之间的时间间隔,并将其转换为整数类型。最后,我们使用简单的数学运算将剩余的秒数转换为天、小时和分钟,并将其输出到控制台。
原文地址: https://www.cveoy.top/t/topic/qeJJ 著作权归作者所有。请勿转载和采集!