首页 > 解决方案 > 如何在swift 4中跳过精确的小时和分钟时间的四舍五入

问题描述

我在 swift 4 中工作,我有一个场景是将时间四舍五入到最近的 5 分钟(如上午 11:12 - 上午 11:15)。对于提到的这种情况,我可以做到这一点。但在这里我的问题是我不应该在“上午 11:15”的时候结束。谁能帮我解决这个问题。在此先感谢。请找到我的以下代码..

func getTimesData{
       let date = Date()
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
        let dateString = df.string(from: date)
        let convertedDate = dateString.convertingStringToDate(date: dateString)
      
        let roundedDate = convertedDate.rounded(minutes: 5, rounding: .ceil)  //Here I am rounding the time.

        let dateAdded = roundedDate.addingTimeInterval(5 * 180)
}

下面的代码是我从 StackOverFlow 本身获得的时间。

enum DateRoundingType {
    case round
    case ceil
    case floor
}

extension Date {
    func rounded(minutes: TimeInterval, rounding: DateRoundingType = .round) -> Date {
        return rounded(seconds: minutes * 60, rounding: rounding)
    }
    func rounded(seconds: TimeInterval, rounding: DateRoundingType = .round) -> Date {
        var roundedInterval: TimeInterval = 0
        switch rounding  {
        case .round:
            roundedInterval = (timeIntervalSinceReferenceDate / seconds).rounded() * seconds
        case .ceil:
            roundedInterval = ceil(timeIntervalSinceReferenceDate / seconds) * seconds
        case .floor:
            roundedInterval = floor(timeIntervalSinceReferenceDate / seconds) * seconds
        }
        return Date(timeIntervalSinceReferenceDate: roundedInterval)
    }
}

标签: iosswiftnsdatensdateformatter

解决方案


无需先使用 DateFormatter 来“烘焙”日期,而是直接调用舍入函数。

let rounded = Date().rounded(minutes: 5, rounding: .ceil)

如果您对 11:15 没有四舍五入到 11:15 有疑问,那可能是因为秒数不完全为 0,所以我建议改用默认值.round

let rounded = Date().rounded(minutes: 5)

推荐阅读