This example will show how to get the current date, current month, current year in Xcode Iphone SDK.
1. Get the current DateTime (NSDate)
2. Convert it to an NSString
3. Split the NSString to an NSArray (by ‘space’)
4. Get first object of the NSArray
5. Again, split it to an NSArray (by ‘-’, hyphen)
6. Access the object at index 0,1,2 to get the current year, month, date respectively.
That’s all
Below is the example:
NSDate *now = [NSDate date]; NSLog(@"now: %@", now); // now: 2011-02-28 09:57:49 +0000 NSString *strDate = [[NSString alloc] initWithFormat:@"%@",now]; NSArray *arr = [strDate componentsSeparatedByString:@" "]; NSString *str; str = [arr objectAtIndex:0]; NSLog(@"strdate: %@",str); // strdate: 2011-02-28 NSArray *arr_my = [str componentsSeparatedByString:@"-"]; NSInteger date = [[arr_my objectAtIndex:2] intValue]; NSInteger month = [[arr_my objectAtIndex:1] intValue]; NSInteger year = [[arr_my objectAtIndex:0] intValue]; NSLog(@"year = %d", year); // year = 2011 NSLog(@"month = %d", month); // month = 2 NSLog(@"date = %d", date); // date = 2 |
Hope it helps
