我有以下代码:
//Age
@IBOutlet weak var daysLabel: UILabel!
@IBOutlet weak var monthsLabel: UILabel!
@IBOutlet weak var yearsLabel: UILabel!
@IBAction func birthday(sender:AnyObject){
var dateComponents = NSDateComponents()
dateComponents.day = 19
dateComponents.month = 12
dateComponents.year = 2015
let certainDate = NSCalendar(identifier: NSCalendarIdentifierGregorian)!.dateFromComponents(dateComponents)!
let durationDateComponents = NSCalendar(identifier: NSCalendarIdentifierGregorian)!.components( [.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: NSDate(), toDate:certainDay, options: [])
yearsLabel.text = "\(durationDateComponents.year)"
monthsLabel.text = "\(durationDateComponents.month)"
daysLabel.text = "\(durationDateComponents.day)"
}
此代码计算自那天起的天数,但它不会倒计时,为什么?我如何实现这一目标?
答案 0 :(得分:0)
我不完全理解你的问题,但这段代码会告诉你我下个生日的日子。 :)
let now = NSDate()
let birthdayDay = 23
let birthdayMonth = 8
let calendar = NSCalendar.currentCalendar()
let thisYear = calendar.component(.Year, fromDate: now)
let bdayComponents = NSDateComponents()
bdayComponents.day = birthdayDay
bdayComponents.month = birthdayMonth
bdayComponents.year = thisYear
var bdayDate = calendar.dateFromComponents(bdayComponents)!
var timeLeft = bdayDate.timeIntervalSinceDate(now)
if (timeLeft < 0) {
bdayComponents.year = thisYear + 1
bdayDate = calendar.dateFromComponents(bdayComponents)!
timeLeft = bdayDate.timeIntervalSinceDate(now)
}
let componentsUntilBday = calendar.components(.Day, fromDate: now, toDate: bdayDate, options: NSCalendarOptions.MatchStrictly)
print("Scott's birthday is in \(componentsUntilBday.day) days!")
更新了在评论中使用建议的代码