Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

medasmx

macrumors member
Original poster
Nov 9, 2008
89
0
I wrote a program that just prints the current date, when a button is pushed. What I would like to do is input a number, then add that number of days to the current calendar date, then print that. NSDate was simple enough to use in the program I already wrote. What methods do I use (to get started) to manipulate dates. Thanks.

Adam
 

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
NSCalendar is the way to go:
Code:
#import <Foundation/Foundation.h>
#import "NSExtendedString.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	NSDateComponents *comps = [[NSDateComponents alloc] init];
	int x = 5;
	[comps setDay:x]; //Use what you want here, set other components as needed
	NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:[NSDate date] options:0];
	NSLog(@"\nValue: %@\n",[newDate description]);
	[comps release];
    [pool release];
    return 0;
}

-Lee

Edit: autorelease pointed to some documentation, my example came from:
http://developer.apple.com/DOCUMENT...lendar/dateByAddingComponents:toDate:options:
 

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
While "simple", it seems very odd that dateByAddingComponents is an instance method, but it does not rely on the NSCalendar it is called on for anything, just the NSDateComponents and NSDate that are passed in.

Hope it serves you well, anyway.

-Lee
 

medasmx

macrumors member
Original poster
Nov 9, 2008
89
0
thanks

Below is the final code I used. It works OK. Thanks very much for the input.

Adam

#import "firsttrydateasm.h"


@implementation firsttrydateasm

-(IBAction)asmbutton:(NSButton*)sender;
{
NSCalendarDate*now=[NSCalendarDate calendarDate];
NSInteger myInt=[input intValue];
NSCalendarDate*myLaterDate=[now dateByAddingYears:0 months:0 days:myInt hours:0 minutes:0 seconds:0];
[output setObjectValue:myLaterDate];
}

@end
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.