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


当前回答

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

其他回答

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

试试下面的方法:

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

只是重新描述一下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        
}

你可以使用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];

我这样做....

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