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


因为这显然是我最喜欢的答案,我将试着编辑它,以包含更多的信息。

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.


如果你想从NSDate中获得单个的NSDateComponents,你肯定需要Itai Ferber建议的解决方案。但如果你想直接从NSDate到NSString,你可以使用NSDateFormatter。


你可以使用NSDateFormatter获取NSDate的独立组件:

NSDateFormatter *df = [[NSDateFormatter alloc] init];

[df setDateFormat:@"dd"];
myDayString = [df stringFromDate:[NSDate date]];

[df setDateFormat:@"MMM"];
myMonthString = [df stringFromDate:[NSDate date]];

[df setDateFormat:@"yy"];
myYearString = [df stringFromDate:[NSDate date]];

如果你想要得到月份的数字而不是缩写,请使用“MM”。如果你想获取整数,使用[myDayString intValue];


只是重新描述一下Itai的优秀(并且工作!)代码,下面是一个示例助手类,它返回给定NSDate变量的年份值。

如您所见,修改这段代码以获得月或日是很容易的。

+(int)getYear:(NSDate*)date
{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];

    int year = [components year];
    int month = [components month];
    int day = [components day];

    return year;
}

(我真不敢相信,在2013年,我们还得自己编写这样的基本iOS日期函数……)

还有一件事:永远不要使用<和>来比较两个NSDate值。

XCode很乐意接受这样的代码(没有任何错误或警告),但其结果是一个彩票。你必须使用"compare"函数来比较nsdate:

if ([date1 compare:date2] == NSOrderedDescending) {
    // date1 is greater than date2        
}

试试下面的方法:

    NSString *birthday = @"06/15/1977";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM/dd/yyyy"];
    NSDate *date = [formatter dateFromString:birthday];
    if(date!=nil) {
        NSInteger age = [date timeIntervalSinceNow]/31556926;
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
        NSInteger day = [components day];
        NSInteger month = [components month];
        NSInteger year = [components year];

        NSLog(@"Day:%d Month:%d Year:%d Age:%d",day,month,year,age);
    }
    [formatter release];

    NSDate *currDate = [NSDate date];
    NSCalendar*       calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents* components = [calendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:currDate];
    NSInteger         day = [components day];
    NSInteger         month = [components month];
    NSInteger         year = [components year];
    NSLog(@"%d/%d/%d", day, month, year);

我这样做....

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);

试试这个……

代码片段:

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

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


如果你的目标是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操作。免责声明,这是我写的文章。


下面是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) 

在Swift 2.0中:

    let date = NSDate()
    let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
    let components = calendar.components([.Month, .Day], fromDate: date)

    let (month, day) = (components.month, components.day)

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

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

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


iOS 8新增功能

ObjC

NSDate *date = [NSDate date];
NSInteger era, year, month, day;
[[NSCalendar currentCalendar] getEra:&era year:&year month:&month day:&day fromDate:date];

斯威夫特

let date = NSDate.init()
var era = 0, year = 0, month = 0, day = 0
NSCalendar.currentCalendar().getEra(&era, year:&year, month:&month, day:&day, fromDate: date)

快2.倍

extension NSDate {
    func currentDateInDayMonthYear() -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "d LLLL yyyy"
        return dateFormatter.stringFromDate(self)
    }
}

你可以用它作为

NSDate().currentDateInDayMonthYear()

输出

6 March 2016

我写这个答案是因为这是唯一的方法,不给你可选的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)

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

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

斯威夫特

更简单的方法获得date的任何元素作为可选String。

extension Date {

  // Year 
  var currentYear: String? {
    return getDateComponent(dateFormat: "yy")
    //return getDateComponent(dateFormat: "yyyy")
  }

  // Month 
  var currentMonth: String? {
    return getDateComponent(dateFormat: "M")
    //return getDateComponent(dateFormat: "MM")
    //return getDateComponent(dateFormat: "MMM")
    //return getDateComponent(dateFormat: "MMMM")
  }


  // Day
  var currentDay: String? {
    return getDateComponent(dateFormat: "dd")
    //return getDateComponent(dateFormat: "d")
  }


  func getDateComponent(dateFormat: String) -> String? {
    let format = DateFormatter()
    format.dateFormat = dateFormat
    return format.string(from: self)
  }


}

let today = Date()
print("Current Year - \(today.currentYear)")  // result Current Year - Optional("2017")
print("Current Month - \(today.currentMonth)")  // result Current Month - Optional("7")
print("Current Day - \(today.currentDay)")  // result Current Day - Optional("10")