Reputation: 50732
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 ?
Upvotes: 4
Views: 5859
Reputation: 33967
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];
Upvotes: 1
Reputation: 21893
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)
Upvotes: 0
Reputation: 107
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 .
Upvotes: 2
Reputation: 90117
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
Upvotes: 17