将NSDate拆分为年月日期

时间:2011-02-12 07:06:25

标签: iphone objective-c cocoa-touch nsdate

如果我的日期是04-30-2006 我如何拆分并获得月,日和年

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

4 个答案:

答案 0 :(得分:17)

你必须使用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];
  

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

没有内置。但你可以为它写一个类别。像这样:

@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

答案 1 :(得分:2)

分拆它很容易

NSString *dateStr = [[NSDate date] description];

NSString *fStr = (NSString *)[[dateStr componentsSeparatedByString:@" "]objectAtIndex:0];
NSString *y = (NSString *)[[fStr componentsSeparatedByString:@"-"]objectAtIndex:0];
NSString *m = (NSString *)[[fStr componentsSeparatedByString:@"-"]objectAtIndex:1];
NSString *d = (NSString *)[[fStr componentsSeparatedByString:@"-"]objectAtIndex:2];

这很容易让你得到你想要的东西。

答案 2 :(得分:1)

到目前为止,所有答案都假设您有一个实际的NSDate对象,但在您的帖子中,您说“我有一个像04-30-2006这样的日期”,这可能是一个字符串。如果它是一个字符串,那么Abizem的答案是最接近你想要的答案:

NSString* dateString = @"04-30-2006";
NSArray* parts = [dateString componentsSeparatedByString: @"-"];
NSString* month = [parts objectAtIndex: 0];
NSString* day = [parts objectAtIndex: 1];
NSString* year = [parts objectAtIndex: 2];

答案 3 :(得分:0)

或者,使用NSDateFormatter

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSDate *now = [NSDate date];

[formatter setDateFormat:@"MM"];
NSString *month = [formatter stringFromDate:now];
[formatter setDateFormat:@"dd"];
NSString *day = [formatter stringFromDate:now];
[formatter setDateFormat:@"yyyy"];
NSString *year = [formatter stringFromDate:now];

[formatter release];

(代码在这里输入;警告实现者)