iOS 开发: Objective-C 计算剩余时间 (天、小时、分钟)
以下是一个 iOS 开发中,使用 Objective-C 语言编写的计算剩余时间的示例代码:
// 获取当前时间
NSDate *currentDate = [NSDate date];
// 设置目标日期
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:2022];
[components setMonth:1];
[components setDay:1];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *targetDate = [calendar dateFromComponents:components];
// 计算剩余时间
NSTimeInterval remainingTimeInterval = [targetDate timeIntervalSinceDate:currentDate];
// 将剩余时间转换为天、小时和分钟
NSInteger remainingDays = remainingTimeInterval / (60 * 60 * 24);
NSInteger remainingHours = (NSInteger)(remainingTimeInterval / (60 * 60)) % 24;
NSInteger remainingMinutes = (NSInteger)(remainingTimeInterval / 60) % 60;
// 输出剩余时间
NSString *remainingTime = [NSString stringWithFormat:'%ld天 %ld小时 %ld分钟', (long)remainingDays, (long)remainingHours, (long)remainingMinutes];
NSLog(@'%@', remainingTime);
这段代码首先获取当前时间,然后设置一个目标日期(这里设置为 2022 年 1 月 1 日),然后使用 timeIntervalSinceDate: 方法计算当前时间与目标日期之间的时间间隔(以秒为单位)。
接下来,将时间间隔转换为天、小时和分钟。其中,剩余天数通过将时间间隔除以一天的秒数(60 秒 * 60 分钟 * 24 小时)得到,剩余小时通过将时间间隔除以一小时的秒数(60 秒 * 60 分钟)取模 24 得到,剩余分钟通过将时间间隔除以一分钟的秒数(60 秒)取模 60 得到。
最后,将剩余天数、小时和分钟拼接成字符串,并输出到控制台。
原文地址: https://www.cveoy.top/t/topic/qeJH 著作权归作者所有。请勿转载和采集!