Split NSDate into year month date

时光怂恿深爱的人放手 提交于 2019-12-19 03:39:07

问题


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 ?


回答1:


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



回答2:


to split it is easy

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

this will be easy to get things what you want basically .




回答3:


All the answers so far assume you have an actual NSDate object, but in your post you say, "I have a date like 04-30-2006" which could be a string. If it is a string then Abizem's answer is the closest to what you want:

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



回答4:


Or, using 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];

(code typed right here; caveat implementor)



来源:https://stackoverflow.com/questions/4976822/split-nsdate-into-year-month-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!