我有一个带有计时器的应用
我有2个参数(例如(:
creationDate
:2018-02-16 17:06:10 UTC'端':2018-02-16 15:07:09 UTC
计时器应显示2 Date
s。
我尝试过:
let duration = self.creationDate.timeIntervalSince(self.endDate)
let timePassed = self.creationDate.timeIntervalSinceNow
let percent = (timePassed * 100) / duration
但是我得到的信息不正确。
有人知道我的算法怎么了?谢谢!
您的参考日期是StartDate而不是终结:
let duration = self.endDate.timeIntervalSince(self.creationDate)
let timePassed = Date().timeIntervalSince(self.creationDate)
let percent = (duration - timePassed) / duration * 100
我希望这会有所帮助(我重命名为示例中的创建/结束变量以使答案更清晰(
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
另外,请注意,在您的示例中,日期结束日期是在创建日期之前。
当我不得不写这样的东西时,我更喜欢变得更加愚蠢,plod脚和系统性。这是一个示威。我们将计算上一个生日和下一个生日之间的距离:
// 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%
注意"夹具"步骤;这将消除您的局外结果。