Thursday, June 13, 2013

NSCalendar NSWrapCalendarComponents example in Objective C (iOS).


NSCalendar NSWrapCalendarComponents

NSDateComponents wrapping behavior
The wrapping option specifies wrapping behavior for calculations involving NSDateComponents objects.

enum
{
NSWrapCalendarComponents = kCFCalendarComponentsWrap,
};
Constants
NSWrapCalendarComponents
Specifies that the components specified for an NSDateComponents object should be incremented and wrap around to zero/one on overflow, but should not cause higher units to be incremented.

NSCalendar NSWrapCalendarComponents example.
You need to use NSCalendar class for calendar calculations:

NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comp = [[[NSDateComponents alloc] init] autorelease];
[comp setMonth: 1];
NSDate* newDate = [gregorian dateByAddingComponents:comp toDate:oldDate options:NSWrapCalendarComponents];

Example of [NSCalendar NSWrapCalendarComponents].
// Subtract one day from the current date (this compensates for daylight savings time, etc, etc.)
- (NSDate *)dateBySubtractingOneDayFromDate:(NSDate *)date {
    NSCalendar *cal = [NSCalendar currentCalendar];

    NSDateComponents *minusOneDay = [[NSDateComponents alloc] init];
    [minusOneDay setDay:-1];
    NSDate *newDate = [cal dateByAddingComponents:minusOneDay
                                           toDate:date
                                          options:NSWrapCalendarComponents];
    return newDate;
}

NSCalendar NSWrapCalendarComponents example.
NSDateComponents *daysToAdd = [[[NSDateComponents alloc] init] autorelease];
daysToAdd.day = 23;

NSDate *derivedData =
      [CURRENTC dateByAddingComponents:daysToAdd
                toDate:sourceDate
                options:NSWrapCalendarComponents];

End of NSCalendar NSWrapCalendarComponents example article.