iOS开发:秒数转换为天、小时、分钟 (OC代码)
可以使用NSDateComponents类来实现时间秒数转换为天小时分钟的功能,以下是相关的OC代码示例:
// 输入时间秒数,返回天、小时和分钟的字符串
- (NSString *)convertSecondsToDHM:(NSInteger)seconds {
// 创建一个日历对象
NSCalendar *calendar = [NSCalendar currentCalendar];
// 创建NSDateComponents对象
NSDateComponents *components = [[NSDateComponents alloc] init];
// 设置秒数
components.second = seconds;
// 将秒数转换为NSDate对象
NSDate *date = [calendar dateFromComponents:components];
// 获取天、小时和分钟的数值
NSInteger days = [calendar component:NSCalendarUnitDay fromDate:date];
NSInteger hours = [calendar component:NSCalendarUnitHour fromDate:date];
NSInteger minutes = [calendar component:NSCalendarUnitMinute fromDate:date];
// 拼接天、小时和分钟的字符串
NSString *result = [NSString stringWithFormat:'%ld天%ld小时%ld分钟', (long)days, (long)hours, (long)minutes];
return result;
}
使用示例:
NSString *timeString = [self convertSecondsToDHM:366600];
NSLog(@'%@', timeString);
输出结果:
4天4小时10分钟
原文地址: http://www.cveoy.top/t/topic/qeHZ 著作权归作者所有。请勿转载和采集!