倒计时迅速返回错误的天数

Posted

技术标签:

【中文标题】倒计时迅速返回错误的天数【英文标题】:Countdown returning wrong amount of days in swift 【发布时间】:2020-05-19 21:28:01 【问题描述】:

我正在尝试以快速获取天数、小时、分钟和秒数的方式实现对特定日期的倒计时,但由于某种原因,我的实现在事件发生前返回了错误的天数,但返回了正确的小时数,分钟和秒。我不确定这里出了什么问题:

let date = Date()

let calendar = Calendar.current

let components = calendar.dateComponents([.second, .minute, .hour, .day], from: date as Date)

let currentDate = calendar.date(from: components)

let userCalendar = Calendar.current

let openingNight = NSDateComponents()
openingNight.year = 2020
openingNight.month = 9
openingNight.day = 10
openingNight.hour = 20
openingNight.minute = 30
openingNight.second = 0

let opener = userCalendar.date(from: openingNight as DateComponents)

let difference = calendar.dateComponents([.second, .minute, .hour, .day], from: currentDate!, to: opener!)

let daysLeft = difference.day
let hoursLeft = difference.hour
let minutesLeft = difference.minute
let secondsLeft = difference.second

daysLabel.text = "\(daysLeft!)"
hourLabel.text = "\(hoursLeft!)"
minuteLabel.text = "\(minutesLeft!)"
secondLabel.text = "\(secondsLeft!)"

返回 737661 天 4 小时 2 分 28 秒

【问题讨论】:

预期的结果应该是什么? 113 天 4 小时 2 分钟 28 秒 您的 currentDate 是“1 月 19 日 1 日下午 5:36”。这就是你得到这么多天的原因。 【参考方案1】:

currentDate 的数据组件中缺少月份和年份。这将给出正确的差异(这里仍然是 5 月 19 日,所以距离 9 月 10 日还有 114 天)。

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.second, .minute, .hour, .day, .month, .year], from: date as Date)
let currentDate = calendar.date(from: components)
let userCalendar = Calendar.current

let openingNight = NSDateComponents()
openingNight.year = 2020
openingNight.month = 9
openingNight.day = 10
openingNight.hour = 20
openingNight.minute = 30
openingNight.second = 0

let opener = userCalendar.date(from: openingNight as DateComponents)

let difference = calendar.dateComponents([.second, .minute, .hour, .day], from: currentDate!, to: opener!)

let daysLeft = difference.day
let hoursLeft = difference.hour
let minutesLeft = difference.minute
let secondsLeft = difference.second

print(difference) // day: 114 hour: 2 minute: 34 second: 6 isLeapMonth: false 

【讨论】:

以上是关于倒计时迅速返回错误的天数的主要内容,如果未能解决你的问题,请参考以下文章

php 天数碳差(倒计时)

如何在iphone sdk中使用日期倒计时来计算天数[关闭]

JS实现倒计时(天数,时,分,秒)

JS实现倒计时(天数,时,分,秒)

倒计时效果——天数

iOS 14 Text() 带天数计时器