PDA

View Full Version : cocoa date manipulation NSDate




medasmx
Dec 4, 2008, 07:09 PM
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



autorelease
Dec 4, 2008, 09:12 PM
Documentation is your friend:

http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSCalendarDate_Class/Reference/Reference.html

dateByAddingYears:months:days:hours:minutes:seconds: is what you want to use.

(Edit: Apparently the use of NSCalendarDate isn't recommended and may become deprecated; however, it's an easy way to achieve what you want.)

lee1210
Dec 4, 2008, 09:23 PM
NSCalendar is the way to go:

#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/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/Reference/NSCalendar.html#//apple_ref/occ/instm/NSCalendar/dateByAddingComponents:toDate:options:

autorelease
Dec 5, 2008, 02:46 PM
Thanks Lee. Never used NSCalendar myself, looks like it actually involves less code than NSCalendarDate. Awesome!

lee1210
Dec 5, 2008, 04:29 PM
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
Dec 6, 2008, 08:10 PM
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