只要这么做就不会再浪费更多美好的生命在处理这件事情上,如下所示...
Swift 1.x
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: date)
let year = components.year
let month = components.month
let day = components.day
Swift 2.x
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day , .Month , .Year], fromDate: date)
let year = components.year
let month = components.month
let day = components.day
print(year)
print(month)
print(day)
Swift 3.x
//作为 swift 3 的一个特色,苹果移除了 NS,让代码更简单了
//现在的代码会是:
let date = Date()
let calendar = Calendar.current
let year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
可以使用这里提供的多个变量来组成多种日期组件:https://developer.apple.com/reference/foundation/nsdatecomponents