【发布时间】:2014-03-05 18:37:47
【问题描述】:
我的问题与下面代码 sn-p 中给出的 NSDateComponents 操作的时间配置文件有关。
- 我有一个迭代大量 NSDate 对象的方法
- 该方法的一部分要求我丢弃每个日期的小时、分钟和秒。
-
为此,我有 3 个步骤:
- 我从原始日期创建了一个 NSDateComponents 对象。
- 我将 H:M:S 元素设置为 0
- 我根据需要将 H:M:S 设置为 0 的新日期对象
问题:
上面的步骤 1 和 3 占用了我整个方法执行时间的很大一部分,分别为 22.4% 和 56.8%。
我正在寻找有关如何优化这部分代码的建议,或者寻找可能表现更好的将 H:M:S 归零的替代方法。
NSDate* date = [[NSDate alloc] init];
// Next line takes 22.4% of the overall method execution time
NSDateComponents* components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit
| NSDayCalendarUnit | NSHourCalendarUnit
| NSSecondCalendarUnit) fromDate:date];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
// Next line takes 56.8% of the overall method execution time
date = [calendar dateFromComponents:components];
【问题讨论】:
-
如果你想粗暴一点(纯粹主义者会作呕),而且你不介意在 UTC 工作(或多或少),你可以简单地提取 NSTimeInterval,除以秒数在一天中,发言,乘以一天中的秒数,然后转换回 NSDate。如果您愿意,可以在一行(稍长)中完成。
-
UTC 很好。我会在早上实现这个,看看效果如何。
-
这非常适合将 H:M:S 归零。查看另一个我想保留小时值的用例,我开始得到有趣的结果。不是我问的问题,而是值得注意的观察如果我尝试转换 2014-03-03 01:30:00 我得到 2014-03-03 00:59:44
标签: ios nsdate nsdatecomponents