NSDate: Working with dates in Cocoa, creating and decomposing

Autor: | Última modificación: 11 de noviembre de 2022 | Tiempo de Lectura: 1 minutos
Temas en este post: ,

Create a NSDate from its components (day, month, year)

You don’t use a init method in NSDate, instead, you use a method of NSCalendar (dateFromComponents:):

Method that initializes a NSDate form an ISO 8601 date representation (YYYYMMDD):

-(id) initWithISO8601Date: (NSString *) iso8601Date{
    // Takes a date in the YYYYMMDD form
    if ([iso8601Date length] == 8 ) {
        int year = [[iso8601Date substringWithRange:NSMakeRange(0, 4)] integerValue];
        int month = [[iso8601Date substringWithRange:NSMakeRange(4, 2)] integerValue];
        int day = [[iso8601Date substringWithRange:NSMakeRange(6,2)] integerValue];

        NSDateComponents *comps = [[NSDateComponents alloc] init];
        [comps setYear:year];
        [comps setMonth:month];
        [comps setDay:day];

        NSCalendar *cal = [NSCalendar currentCalendar];
        [cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
        self = [cal dateFromComponents:comps];

        [comps release];
    }else{
        self = nil;
        [NSException raise:@"Wrong ISO8601 format"
                    format:@"Should be in YYYYMMDD format, instead got %@", iso8601Date];
    }

    return self;

}

Tokenize a NSDate into its components (day, month, year, etc…)

You also use a method form NSCalendar(components:fromDate):

    NSDate *today = [[[NSDatealloc] init] autorelease];
    NSDateComponents *tokens = [[NSCalendarcurrentCalendar]
                                components:(NSYearCalendarUnit |
                                            NSMonthCalendarUnit |
                                            NSDayCalendarUnit |
                                            NSHourCalendarUnit |
                                            NSMinuteCalendarUnit |
                                            NSSecondCalendarUnit)
                                fromDate:today];

    NSLog(@"%d %d %d", [tokens year], [tokens month], [tokens day]);

Tokenize the difference between 2 dates into its components (day, month, year, etc…)

Use a similar method from NSCalendar: components:fromDate:toDate:options:

    NSDate *today = [[[NSDatealloc] init] autorelease];
    NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
    [comps setYear:1970];
    [comps setMonth:1];
    [comps setDay:7];

    NSCalendar *cal = [NSCalendarcurrentCalendar];
    [cal setTimeZone: [NSTimeZonetimeZoneWithAbbreviation:@"GMT"]];

    NSDate *daysOfOld = [cal dateFromComponents:comps];

    comps = [cal components:(NSYearCalendarUnit |
                             NSMonthCalendarUnit |
                             NSDayCalendarUnit |
                             NSHourCalendarUnit |
                             NSMinuteCalendarUnit |
                             NSSecondCalendarUnit)
                   fromDate:daysOfOld toDate:today
                    options:0];    NSLog(@"You are a %d years %d months %d days %d hours %d minutes and %d seconds old fart!",
          [comps year],
          [comps month],
          [comps day],
          [comps hour],
          [comps minute],
          [comps second]);