Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate, NSCalendar and NSDateComponents timing

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 :-)

like image 664
clement Avatar asked Dec 21 '22 15:12

clement


2 Answers

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

like image 76
visakh7 Avatar answered Dec 24 '22 06:12

visakh7


  1. Add more units to NSDayCalendarUnit | NSWeekdayCalendarUnit - you are not requesting month or year, therefore they are invalid!

  2. Add/subtract a NSDateComponents object configured for 1 day and [NSCalendar dateByAddingComponents:toDate:options:]. Alternatively, and probably just as correct, use [NSDate dateWithTimeInterval:sinceDate:]

like image 34
Steven Kramer Avatar answered Dec 24 '22 04:12

Steven Kramer