Search code examples
objective-ciosnsdatensdateformatternsdatecomponents

Struggling to store a date for later use


Hi I'm very new to iOS programming and am playing around with dates (todays date and a date 1 year from now).

Here's the code i'm dabbling with.

NSCalendar * calendar = [NSCalendar currentCalendar];//Create a calendar
NSDate *todaysDate = [[NSDate alloc]init]; //get todays date
NSString *dateToday = [NSString stringWithFormat:@"%@",todaysDate];//convert it to a string
NSDateFormatter *df = [[NSDateFormatter alloc] init];// create a formatter
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ" ];//input how the date looks as a string
myDate = [df dateFromString: dateToday];// change it back to a proper NSDate

NSDateComponents *components = [[NSDateComponents alloc] init]; // create the components
[components setYear:1];//add 1 year
nextYear = [calendar dateByAddingComponents:components toDate:todaysDate options:0]; // build the year from component into a variable


dateNextYear = [NSString stringWithFormat:@"%@",nextYear];//convert it to a string
NSDateFormatter *yearFormat = [[NSDateFormatter alloc] init];// create a formatter
[yearFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ" ];//input how the date looks as a string
myDateInTheFuture = [yearFormat dateFromString: dateNextYear];// change it back to a proper NSDate


NSLog(@" next years date is %@ ", myDateInTheFuture);
[yearFormat release];
[components release];
[todaysDate release];

I can get the current date and the future date 1 year from now, but i'm unsure how i would store the future date for comparison, i know i can use the "compare" item for NSDate to check, but when i set the future date to a variable every time it runs it stays relative 1 year apart from what i'm checking it against which is todays date. Its 3am where i am and my brain is mush so apologises in advance if this is the simplest thing ever and i just can't see it.

Its my first post so go easy on me please. Thanks


Solution

  • I am not entirely sure what you are trying to do, but this is what I gather:

    You want to take the current date, add a year to it, and manipulate the resulting date.

    Please notify me if this is not correct.

    For this, try the following:

    NSDate *todayDate = [NSDate date]; //Create a date that is set to today
    NSDate *resultingDate = [calendar dateByAddingTimeInterval:31556926; //Take the current date and add the amount of seconds in a year to it
    

    If you want to store this permanently, use the NSUserDefaults:

    to set:

    [userDefaults setObject:resultingDate forKey:@"storedDate"];
    

    Hope this helps,

    HBhargava

    to get:

    NSDate *returnedDate = [userDefaults dateForKey:@"storedDate"];