因为这显然是我最喜欢的答案,我将试着编辑它,以包含更多的信息。
Despite its name, NSDate in and of itself simply marks a point in machine time, not a date. There's no correlation between the point in time specified by an NSDate and a year, month, or day. For that, you have to refer to a calendar. Any given point in time will return different date information based on what calendar you're looking at (dates are not the same in both the Gregorian and Jewish calendars, for instance), and while the Gregorian calendar is the most widely used calendar in the world - I'm assuming - we're a little biased that NSDate should always use it. NSDate, luckily, is far more bipartisan.
获取日期和时间将必须通过NSCalendar,正如你提到的,但有一个更简单的方法来做它:
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
它生成一个NSDateComponents对象,其中包含来自当前系统日历的日、月和年。(注意:这不一定是当前用户指定的日历,只是默认的系统日历。)
当然,如果你使用不同的日历或日期,你可以很容易地更改它。可用日历和日历单元的列表可以在NSCalendar类引用中找到。更多关于NSDateComponents的信息可以在NSDateComponents类参考中找到。
作为参考,从NSDateComponents中访问单个组件相当简单:
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
You just have to be mindful: NSDateComponents won't contain valid information for any fields you ask for unless you generated them with that valid information (i.e. request NSCalendar to provide that information with NSCalendarUnits). NSDateComponents contain no reference information in and of themselves - they're just simple structures that hold numbers for you to access. If you want to also get an era, for instance, out of NSDateComponents, you'll have to feed the generator method from NSCalendar with the NSCalendarUnitEra flag.