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?
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];
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.
精彩评论