计算2个Swift Date对象之间的百分比

时间:2018-02-16 15:14:00

标签: ios iphone swift algorithm cocoa-touch

我有一个带有计时器的应用程序,显示提醒的创建日期到结束日期之间的百分比。

我有2个参数(例如):

creationDate:2018-02-16 17:06:10 UTC 'endDate':2018-02-16 15:07:09 UTC

计时器应显示2 Date之间已经过了多少百分比。

我试过了:

let duration = self.creationDate.timeIntervalSince(self.endDate)
let timePassed = self.creationDate.timeIntervalSinceNow
let percent = (timePassed * 100) / duration

但我收到的信息不正确。

有人知道我的算法出了什么问题吗?谢谢!

3 个答案:

答案 0 :(得分:1)

我希望这会有所帮助(我从您的示例中重命名了创建/结束变量以使答案更清晰)

let initialDate = Date().addingTimeInterval(-1000)
let now = Date()
let finalDate = Date().addingTimeInterval(10000)

let totalDuration = finalDate.timeIntervalSince(initialDate)
let currentRemainingDuration = finalDate.timeIntervalSince(now)

let percent = (currentRemainingDuration/totalDuration) * 100

另请注意,在您的示例中,日期结束日期是在创建日期之前。

答案 1 :(得分:1)

你引用的日期是startDate而不是endDate:

let duration = self.endDate.timeIntervalSince(self.creationDate)
let timePassed = Date().timeIntervalSince(self.creationDate)
let percent = (duration - timePassed) / duration * 100

答案 2 :(得分:1)

当我必须写这样的东西时,我更喜欢变得更愚蠢,更笨拙和更系统。这是一个演示。我们将计算我上一个生日和下一个生日之间的距离:

// initial conditions
let greg = Calendar(identifier: .gregorian)
let dc1 = DateComponents(calendar: greg, year: 2017, month: 8, day: 10)
let dc2 = DateComponents(calendar: greg, year: 2018, month: 8, day: 10)
let dstart = greg.date(from: dc1)!
let dend = greg.date(from: dc2)!
let target = Date() // now

// okay, ready to go! convert all dates to time intervals
let dend_ti = dend.timeIntervalSince(dstart)
let target_ti = target.timeIntervalSince(dstart)
// target is what percentage of dend?
let x = target_ti * 100 / dend_ti
// clamp between 0 and 100
let result = min(max(x, 0), 100)
// print result nicely
print(Int(result), "%", separator:"") // 52%

注意“夹紧”步骤;这将消除你的越界负面结果。