快速计算到另一个日期的天数,小时数,分钟数和秒数。
我已经尝试过在函数中使用swifts datecomponents,但是它为我返回的天数不正确。
@objc func createCountdown(){
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.day, .hour, .minute, .second], from: date)
let currentDate = calendar.date(from: components)
let userCalendar = Calendar.current
var birthdayDate = DateComponents()
//Get user's birthday
birthdayDate.month = 4
birthdayDate.day = 16
birthdayDate.hour = 0
birthdayDate.minute = 0
let birthday = userCalendar.date(from: birthdayDate as DateComponents)
let BirthdayDifference = calendar.dateComponents([.day, .hour, .minute, .second], from: currentDate!, to: birthday!)
let daysLeft = BirthdayDifference.day
let hoursLeft = BirthdayDifference.hour
let minutesLeft = BirthdayDifference.minute
let secondsLeft = BirthdayDifference.second
daysLabel.text = String(daysLeft!)
hoursLabel.text = String(hoursLeft!)
minutesLabel.text = String(minutesLeft!)
secondsLabel.text = String(secondsLeft!)
}
代码中的测试日期为生日值。我只是想从当前日期开始将天,小时,分钟和秒倒数到指定的生日。
此输出为74天,但显然今天从2018年12月31日到2019年4月16日超过74天。那是大约105天,而不是74天。任何建议都将不胜感激。
谢谢。
答案 0 :(得分:1)
您需要根据生日那天和月份找出下一个生日。您可以使用日历的方法nextDate(after: Date, matching: DateComponents)
func nextDate(after date: Date, matching components: DateComponents, matchingPolicy: Calendar.MatchingPolicy, repeatedTimePolicy: Calendar.RepeatedTimePolicy = default, direction: Calendar.SearchDirection = default) -> Date?
let birthDateCoponents = DateComponents(month: 4, day: 16)
let nextBirthDate = Calendar.current.nextDate(after: Date(), matching: birthDateCoponents, matchingPolicy: .nextTime)!
let difference = Calendar.current.dateComponents([.day, .hour, .minute, .second], from: Date(), to: nextBirthDate)
difference.day // 105
difference.hour // 2
difference.minute // 5
difference.second // 30
向用户显示它时,可以将DateComponentsFormatter与相应的unitsStyle
一起使用。您可以在下面看到使用.full
样式并将单位限制为.day, .hour, .minute, .second
时的外观:
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.day, .hour, .minute, .second]
formatter.unitsStyle = .full
formatter.string(from: Date(), to: nextBirthDate) // "105 days, 1 hour, 44 minutes, 36 seconds"