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

clement
  • 4,204
  • 10
  • 65
  • 133

2 Answers2

9
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

visakh7
  • 26,380
  • 8
  • 55
  • 69
2
  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:]

Steven Kramer
  • 8,473
  • 2
  • 37
  • 43
  • Great, please accept the answer so people will be able to find it... did you get the point about `dateByAddingComponents`? – Steven Kramer Apr 12 '11 at 11:32
  • 1
    Don't try value based coding in Cocoa - everything is a reference (i.e. a pointer to an object). Use `NSDate* newDate = [calendar dateByAddingComponents: oneDay toDate: self.date options: 0];` – Steven Kramer Apr 12 '11 at 14:39
  • Are you sure? You might want to measure this first, tons of objects are getting created all the time in most apps. – Steven Kramer Apr 12 '11 at 15:23
  • 1
    Don't worry. Your users can't swipe quickly enough to notice the object creation. Up to a few thousand object creations/deallocations per second (at least!) should not be noticeable. – Steven Kramer Apr 12 '11 at 15:55