将NSDate拆分为年份日期 [英] Split NSDate into year month date

查看:102
本文介绍了将NSDate拆分为年份日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个日期,如04-30-2006
如何分割和获得月,日和年

If I have a date like 04-30-2006 how can I split and get month, day and year

还有那里的任何直接方式比较年份?

Alsois there any direct way of comparing the years ?

推荐答案

您必须使用NSDateComponents。像这样:

you have to use NSDateComponents. Like this:

NSDate *date = [NSDate date];
NSUInteger componentFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [[NSCalendar currentCalendar] components:componentFlags fromDate:date];
NSInteger year = [components year];
NSInteger month = [components month];
NSInteger day = [components day];




还有什么直接比较年份的方法吗?

Alsois there any direct way of comparing the years ?

未内置。但是你可以为它编写一个类别。像这样:

not built in. But you could write a category for it. Like this:

@interface NSDate (YearCompare)
- (BOOL)yearIsEqualToDate:(NSDate *)compareDate;
@end

@implementation NSDate (YearCompare)

- (BOOL)yearIsEqualToDate:(NSDate *)compareDate {
    NSDateComponents *myComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:self];
    NSDateComponents *otherComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:compareDate];
    if ([myComponents year] == [otherComponents year]) {
        return YES;
    }
    return NO;
}

@end

这篇关于将NSDate拆分为年份日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆