NSDate, NSCalendar and NSDateComponents timing

clement picture clement · Apr 12, 2011 · Viewed 8.4k times · Source
NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+2"]];

NSDateComponents *dateComponents = [calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];    

NSInteger day = [dateComponents day];
NSInteger month = [dateComponents month];
NSInteger year = [dateComponents year];

 NSLog(@" %i %i %i ", day, month, year);

That code show me "12 2147483647 2147483647"

How can I get the month and year (integer)

How can add/forward one day? (if we are the first of the month too!)

Thant you for your attention :-)

Answer

visakh7 picture visakh7 · Apr 12, 2011
NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];

NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];

[calendar release];

hope this helps