如何在 swift 4 中精确的小时和分钟到来时跳过时间的四舍五入

How to skip the rounding of the time when it is coming exact hours and minutes in swift 4

我在 swift 4 工作,我有一个场景是将时间四舍五入到最接近的 5 分钟(比如 11:12 AM - 11:15 AM)。对于上述场景,我能够做到这一点。但我的问题是我不应该在“11:15 AM”的时候四舍五入。谁能帮我解决 Advance.Please 中的这个 issue.Thanks 找到我下面的代码..

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)
}

我在一段时间内使用的以下代码是我从 Whosebug 本身获得的。

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)
    }
}

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

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

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

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