iphone - 将 NSDate 拆分为年月日

标签 iphone objective-c cocoa-touch nsdate

如果我有一个像 04-30-2006 这样的日期 我怎样才能拆分并得到月、日和年

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

最佳答案

你必须使用 NSDateComponents。像这样:

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 ?

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

@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

关于iphone - 将 NSDate 拆分为年月日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4976822/

相关文章:

ios - 使用 NSJSONSerialization 从 json 反序列化图像

ios - RestKit 0.20.0-rc1 - 如何映射多个错误参数?

iPhone SDK : How to add an image to a UIBarButton?

iphone - 这个声明有漏洞吗?

ios - Cell 在 iPad 上没有正确隐藏?

objective-c - 在 Objective C 中向 NSMutableArray 添加对象时遇到问题

ios - 重写不在 super 中的方法

iphone - UITabBarItem 图像的最大尺寸是多少?

ios - 如何在不使用最新 FBSDK 的 iOS 应用程序中将 Safari 浏览器重定向到 Facebook

推送或弹出新 View Controller 时,iOS 7 自定义 UINavigationBar TitleView 移动