Split NSDate on the day of the month

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

Is there any direct way to compare years?

+4
source share
4 answers

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

Is there any direct way to compare years?

not built in. But you can 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 
+17
source

easy to smash it

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

It will be easy to get what you want mostly.

+2
source

All answers still assume that you have a real NSDate object, but in your message you say: "I have a date, for example 04-30-2006," which may be a string. If this is a string, then Abizem's answer is 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]; 
+1
source

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 is listed here, caveat developer)

0
source

Source: https://habr.com/ru/post/1339452/


All Articles