Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split NSDate into year month date

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 ?

like image 294
copenndthagen Avatar asked Nov 30 '22 08:11

copenndthagen


2 Answers

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
like image 73
Matthias Bauch Avatar answered Dec 12 '22 15:12

Matthias Bauch


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 .

like image 23
Ramesh India Avatar answered Dec 12 '22 13:12

Ramesh India