我在日,时和分上收到错误。这是代码:
let dayCalendarUnit = calendar.components([NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: date)
//here we change the seconds to hours,minutes and days
let CompetitionDayDifference = NSDateComponentsFormatter()
CompetitionDayDifference.unitsStyle = .Full
CompetitionDayDifference.allowedUnits = [.Day, .Hour, .Minute]
let string = CompetitionDayDifference.stringFromDate(currentDate!, toDate: competitionDay)
//finally, here we set the variable to our remaining time
var daysLeft = CompetitionDayDifference.Day
var hoursLeft = CompetitionDayDifference.Hour
var minutesLeft = CompetitionDayDifference.Minute
最佳答案
发生错误是因为您试图直接从日期格式器获取日期组件属性,而这是不可能的。
实际上,您不需要日期格式化程序。只是从差异中获取组件
let competitionDayDifference = calendar.components([.Day, .Hour, .Minute],
fromDate: currentDate!, toDate: competitionDay, options: NSCalendarOptions())
//finally, here we set the variable to our remaining time
let daysLeft = competitionDayDifference.day
let hoursLeft = competitionDayDifference.hour
let minutesLeft = competitionDayDifference.minute