我在将一些代码从Objective-C转换为Swift时遇到了一些麻烦。我试图制作一个告诉我多大年纪的标签。我想给我的生日,我会回到几天,几小时,几分钟,几秒钟,我已经过了多长时间。代码是:
@IBAction func birthday(sender:AnyObject){
var dateComponents = NSDateComponents()
dateComponents.day = 19
dateComponents.month = 12
dateComponents.year = 1999
var calender = NSCalendar(identifier: NSGregorianCalendar)
var birthDate = calender!.dateFromComponents(dateComponents)
var currentDate = NSDate.date()
var durationDateComponents = calender.components(NSCalenderUnit.CalenderUnitDay, fromDate: birthDate!,
toDate: currentDate,
options: nil)
var numberOfDaysFromBirth = durationDateComponents.day
messageLabel.text = "\(numberOfDaysFromBirth)"
}
答案 0 :(得分:0)
var dateComponents = NSDateComponents()
dateComponents.day = 19
dateComponents.month = 12
dateComponents.year = 1999
let birthDate = NSCalendar(identifier: NSGregorianCalendar)!.dateFromComponents(dateComponents)!
let durationDateComponents = NSCalendar(identifier: NSGregorianCalendar)!.components( .CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay | .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond, fromDate: birthDate, toDate: NSDate(), options: nil)
let numberOfyearsFromBirth = durationDateComponents.year // 15
let numberOfMonthsFromBirth = durationDateComponents.month // 3
let numberOfDaysFromBirth = durationDateComponents.day // 17
let numberOfHoursFromBirth = durationDateComponents.hour // 1
let numberOfminutesFromBirth = durationDateComponents.minute // 28
let numberOfsecondsFromBirth = durationDateComponents.second // 34