我怎么能得到一个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的年/月/日这样简单的事情来说,这似乎是一大堆麻烦。还有其他解决办法吗?


当前回答

从iOS 8.0(和OS X 10)开始,你可以使用component方法来简化获取单个日期组件,如下所示:

int year = [[NSCalendar currentCalendar] component:NSCalendarUnitYear fromDate:[NSDate date]];

应该使事情更简单,希望这是有效地实施。

其他回答

试试这个……

代码片段:

 NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
 int year = [components year];
 int month = [components month];
 int day = [components day];

它给出了当前的年、月、日

我写这个答案是因为这是唯一的方法,不给你可选的NSDateComponent变量和/或强制展开这些变量(也适用于Swift 3)。

斯威夫特3

let date = Date()
let cal = Calendar.current
let year = cal.component(.year, from: date)
let month = cal.component(.month, from: date)
let day = cal.component(.day, from: date)

斯威夫特2

let date = NSDate()
let cal = NSCalendar.currentCalendar()
let year = cal.component(.Year, fromDate: date)
let month = cal.component(.Month, fromDate: date)
let day = cal.component(.Day, fromDate: date)

奖金Swift 3有趣的版本

let date = Date()
let component = { (unit) in return Calendar.current().component(unit, from: date) }
let year = component(.year)
let month = component(.month)
let day = component(.day)

我这样做....

NSDate * mydate = [NSDate date];

NSCalendar * mycalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSCalendarUnit units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;

NSDateComponents * myComponents  = [mycalendar components:units fromDate:mydate];

NSLog(@"%d-%d-%d",myComponents.day,myComponents.month,myComponents.year);

要获得人类可读的字符串(日,月,年),你可以这样做:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *string = [dateFormatter stringFromDate:dateEndDate];

如果你的目标是iOS 8+,你可以使用新的NSCalendar方便方法以更简洁的格式实现这一点。

首先创建一个NSCalendar并使用所需的NSDate。

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [NSDate date];

你可以通过component:fromDate单独提取组件:

NSInteger year = [calendar component:NSCalendarUnitYear fromDate:date];
NSInteger month = [calendar component:NSCalendarUnitMonth fromDate:date];
NSInteger day = [calendar component:NSCalendarUnitDay fromDate:date];

或者,更简洁地,通过getEra使用NSInteger指针:year:month:day:fromDate:

NSInteger year, month, day;
[calendar getEra:nil year:&year month:&month day:&day fromDate:date];

要了解更多信息和示例,请查看iOS 8中简化的NSDate操作。免责声明,这是我写的文章。