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

时间:2018-02-28 10:26:50

标签: date swift2 nscalendar

我有第一个例子, 12:03 ,第二个例子, 21:56

结束输出给出; 9.88

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

1 个答案:

答案 0 :(得分:1)

如果你以整数格式划分秒数,那么你总是得到大于60的答案。你需要使用DateComponentsFormatter()来获得时间之间的差异:分钟格式。

斯威夫特4:

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