iphone - 将 NSDate 舍入到最接近的 5 分钟

标签 iphone objective-c cocoa

例如我有

NSDate *curDate = [NSDate date];

它的值是上午 9:13。我没有使用 curDate 的年、月和日部分。

我想得到的是时间值是 9:15 的日期;如果我有 9:16 的时间值,我想将它提前到 9:20 等等。

如何使用 NSDate 做到这一点?

最佳答案

这是我的解决方案:

NSTimeInterval seconds = round([date timeIntervalSinceReferenceDate]/300.0)*300.0;
NSDate *rounded = [NSDate dateWithTimeIntervalSinceReferenceDate:seconds];

我做了一些测试,它的速度大约是 Voss 解决方案的十倍。 1M 次迭代大约需要 3.39 秒。这一个在 0.38 秒内完成。 J3RM 的解决方案耗时 0.50 秒。内存使用量也应该是最低的。

并不是说性能就是一切,而是单线。此外,您还可以通过除法和乘法轻松控制舍入。

编辑:要回答这个问题,您可以使用 ceil 正确四舍五入:

NSTimeInterval seconds = ceil([date timeIntervalSinceReferenceDate]/300.0)*300.0;
NSDate *rounded = [NSDate dateWithTimeIntervalSinceReferenceDate:seconds];

编辑:Swift 中的扩展:

public extension Date {

    public func round(precision: TimeInterval) -> Date {
        return round(precision: precision, rule: .toNearestOrAwayFromZero)
    }

    public func ceil(precision: TimeInterval) -> Date {
        return round(precision: precision, rule: .up)
    }

    public func floor(precision: TimeInterval) -> Date {
        return round(precision: precision, rule: .down)
    }

    private func round(precision: TimeInterval, rule: FloatingPointRoundingRule) -> Date {
        let seconds = (self.timeIntervalSinceReferenceDate / precision).rounded(rule) *  precision;
        return Date(timeIntervalSinceReferenceDate: seconds)
    }
}

关于iphone - 将 NSDate 舍入到最接近的 5 分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1149256/

相关文章:

iphone - 为什么我的 NSInteger 对象中会出现奇怪的值?

ios - 使用某种关系保存应用程序数据的最佳方式

cocoa - 调整 ScrollView 上的动画大小

iphone - iOS 应用程序启动画面使用的尺寸是多少?

iphone - 在 Storyboard中使用 UIPageViewController

objective-c - 如何执行 [self.view addSubview : lbl] outside of ViewController Class scope?

cocoa - 将 NSAttributedString 转换为纯文本

objective-c - NSTextField 输入触发 Action

iphone - 关闭 ViewController : not working

objective-c - Google map 路由语法