我怎么能得到一个NSDate对象的年/月/日,没有其他信息?我意识到我可以用类似这样的东西来做这件事:
NSCalendar *cal = [[NSCalendar alloc] init];
NSDateComponents *components = [cal components:0 fromDate:date];
int year = [components year];
int month = [components month];
int day = [components day];
但是对于像获取NSDate的年/月/日这样简单的事情来说,这似乎是一大堆麻烦。还有其他解决办法吗?
下面是Swift的解决方案:
let todayDate = NSDate()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
// Use a mask to extract the required components. Extract only the required components, since it'll be expensive to compute all available values.
let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: todayDate)
var (year, month, date) = (components.year, components.month, components.day)