计算 2 Swift 日期对象之间的百分比

Calculating percentage between 2 Swift Date objects

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

我有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

但我得到的信息是错误的。

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

希望这对您有所帮助(我重命名了您示例中的 creation/end 变量以使答案更清楚)

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

另请注意,在您的示例中,结束日期早于创建日期。

您的参考日期是开始日期而不是结束日期:

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

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

// 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%

注意"clamp"步骤;这将消除您的 out-of-bounds 阴性结果。