cocoa date manipulation NSDate

Discussion in 'Mac Programming' started by medasmx, Dec 4, 2008.

  1. medasmx macrumors member

    Joined:
    Nov 9, 2008
    #1
    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
     
  2. autorelease macrumors regular

    Joined:
    Oct 13, 2008
    Location:
    Achewood, CA
    #2
  3. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #3
    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:
     
  4. autorelease macrumors regular

    Joined:
    Oct 13, 2008
    Location:
    Achewood, CA
    #4
    Thanks Lee. Never used NSCalendar myself, looks like it actually involves less code than NSCalendarDate. Awesome!
     
  5. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #5
    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
     
  6. medasmx thread starter macrumors member

    Joined:
    Nov 9, 2008
    #6
    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
     

Share This Page