swift2 swift 2中两个小时之间的错误计算误差

daupos2t  于 2022-11-06  发布在  Swift
关注(0)|答案(1)|浏览(179)

我有第一个小时示例,12:03,第二个小时示例,21:56
结束输出给出;九点八八分

88大于60分钟这是一个错误,我该如何修复它?我的代码在下面。

let calendar = NSCalendar.currentCalendar()
    if firstHour != nil && secondHour != nil {

    let dateComponents = calendar.components(NSCalendarUnit.Minute, fromDate: firstHour!, toDate: secondHour!, options: [])
    let seconds : Double = Double(dateComponents.minute)
    let clean : Double = (seconds / 60.0)

    let formattern = NSNumberFormatter()
    formattern.maximumFractionDigits = 2
    let cleando  = formattern.stringFromNumber(clean)!

    print(cleando)

    }

    Output : 9.88
czfnxgou

czfnxgou1#

如果您除以整数格式的秒数,那么您得到的结果总是大于60。您需要使用DateComponentsFormatter()来获得以小时为单位的时间差:分钟格式。
雨燕四:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"

let timeAtPress = dateFormatter.date(from: "12:03")

let timeAtPress2 = dateFormatter.date(from: "21:56")

let elapsed = timeAtPress2?.timeIntervalSince(timeAtPress!)

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [ .minute, .second ]
formatter.zeroFormattingBehavior = [ .pad ]

let formattedDuration = formatter.string(from: elapsed!/60)
print(formattedDuration!) // 9:53

相关问题