标签:
看看先:
// 日期格式化对象 NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; // 设置日期格式 fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss"; // 2个日期对象 NSDate *date1 = [fmt dateFromString:@"1970-01-01 00:00:01"]; NSDate *date2 = [fmt dateFromString:@"1970-02-02 01:01:00"]; // 从date1到date2之间走过的秒数 NSInteger interval = [date2 timeIntervalSinceDate:date1]; // 1分钟 = 60秒 NSInteger secondsPerMinute = 60; // 1小时 = 60 * 60秒 = 3600秒 NSInteger secondsPerHour = 60 * secondsPerMinute; // 1天 = 24 * 60 * 60秒 NSInteger secondsPerDay = 24 * secondsPerHour; NSInteger day = interval / secondsPerDay; NSInteger hour = (interval % secondsPerDay) / secondsPerHour; NSInteger minute = ((interval % secondsPerDay) % secondsPerHour) / secondsPerMinute; NSInteger second = interval % secondsPerMinute; NSLog(@"%zd天%zd小时%zd分%zd秒", day, hour, minute, second);
能否将这段代码封装起来,传入一日期对象,返回天,小时,分钟,秒 ?
有几种常见的方法?
推荐使用哪种?
1.指针
指针知识回顾:
int age = 10; int *p ; p = &age; //将100赋值给指针变量p所指向的存储空间 相当于 age = 100 *p = 100;
因此在方法的实现中:
*dayP = interval / secondsPerDay; *hourP = (interval % secondsPerDay) / secondsPerHour; *minuteP = ((interval % secondsPerDay) % secondsPerHour) / secondsPerMinute; *secondP = interval % secondsPerMinute;
在方法的调用中:
NSInteger day = 0; NSInteger hour = 0; NSInteger minute = 0; NSInteger second = 0; [date2 zlf_intervalSinceDate:date1 day:&day hour:&hour minute:&minute second:&second]; NSLog(@"%zd天%zd小时%zd分%zd秒", day, hour, minute, second);
但是这种传入的参数太多,能否只传入日期,返回天,小时,分钟,秒 ?
2.集合 (通过集合装着返回的数据, 但只能装对象)
2.1数组
实现:
NSInteger day = interval / secondsPerDay; NSInteger hour = (interval % secondsPerDay) / secondsPerHour; NSInteger minute = ((interval % secondsPerDay) % secondsPerHour) / secondsPerMinute; NSInteger second = interval % secondsPerMinute; return @[@(day), @(hour), @(minute), @(second)];
调用:
NSArray *interval = [date2 zlf_intervalSinceDate:date1];
NSInteger day = [interval[0] integerValue];
NSInteger hour = [interval[1] integerValue];
NSInteger minute = [interval[2] integerValue];
NSInteger second = [interval[3] integerValue];
NSLog(@"%zd天%zd小时%zd分%zd秒", day, hour, minute, second);
这样调用起来很不友好,乃至调用的时候压根不知道0,1,2,3代表的含义。必须进入到实现文件中查看。
因此可以和枚举一起使用,这样调用起来稍微好些。
定义枚举
typedef enum { /** 天 */ ZLFIntervalIndexDay = 0, /** 小时 */ ZLFIntervalIndexHour = 1, /** 分钟 */ ZLFIntervalIndexMinute = 2, /** 秒 */ ZLFIntervalIndexSecond = 3, } ZLFIntervalIndex;
这样调用起来(至少有提示,知道数组中每个对象的含义):
NSArray *interval = [date2 zlf_intervalSinceDate:date1]; NSInteger day = [interval[ZLFIntervalIndexDay] integerValue]; NSInteger hour = [interval[ZLFIntervalIndexHour] integerValue]; NSInteger minute = [interval[ZLFIntervalIndexMinute] integerValue]; NSInteger second = [interval[ZLFIntervalIndexSecond] integerValue]; NSLog(@"%zd天%zd小时%zd分%zd秒", day, hour, minute, second);
标签:
原文地址:http://www.cnblogs.com/zhangliaofan/p/5196829.html