views:

48

answers:

2

I'm trying to set some components of todays date with NSDateComponent like so:

    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:1];
    [comps setHour:1];
    [comps setMinute:44];
    NSCalendar *cal = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDate *date = [cal dateByAddingComponents:comps toDate:[NSDate date] options:0];
    [comps release];
    NSLog(@"%@", date);

But this example will ADD the time to the current date. Now what I want to do is ADD one day but set the hour and minute to the specified values (no adding). How can I do this?

A: 

Easy: Just use the date property...

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1];
[comps setHour:1];
[comps setMinute:44];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];

Edit: forgot the calendar. From the manual (1st page of NSDateComponents in bold):

Important: An NSDateComponents object is meaningless in itself; you need to know what calendar it is interpreted against, and you need to know whether the values are absolute values of the units, or quantities of the units.

There's also an example of how to use it.

Eiko
This gives null back.
sebrock
Forgot about the calendar... edited to fix it.
Eiko
Not tested but that would probably work as well.
sebrock
A: 

This worked in the end:

NSDateComponents *comp = [[NSCalendar currentCalendar] components:NSYearCalendarUnit
NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];
[comp setDay:[comp day] +1];
[comp setHour: 12];
[comp setMinute: 00];
NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:comp];
sebrock
Actually what I'm doing here is ADDING one day and setting the time to 12:00
sebrock