2

I want to get the date that will be in 45 days from today in objective C - iphone. I'm new in objective C :)

I know that i can do somthing like:

NSString *dateStr = @"Tue, 16 April 2013 13:00:00 +0000";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EE, d LLLL yyyy HH:mm:ss Z"];
NSDate *date = [dateFormat dateFromString:dateStr]; 
[dateFormat release];

But, i do not want a static allocate... it should be dynamic. Every day i need to get in *date variable the date of 45 days from today.

lolo
  • 17,392
  • 9
  • 25
  • 49
  • Look here http://stackoverflow.com/questions/5067785/how-do-i-add-1-day-to-a-nsdate – B.S. Mar 07 '13 at 08:19
  • What is static and what you say dynamic? `[NSDate date]` is always dynamic returns the current date. – Anoop Vaidya Mar 07 '13 at 08:26
  • @George: That is not a good solution, that is accepted there. It doesn't care about daylight, leap seconds etc – Anoop Vaidya Mar 07 '13 at 08:27
  • I mean, i need the date that will be 45 days from today, Every day! not the date of 45 days from today date – lolo Mar 07 '13 at 08:28
  • @lolo: yes every day your date will be +45 from that day, because [NSDate date] will return that day's date and you are adding 45 days to it. :) – Anoop Vaidya Mar 07 '13 at 08:41

1 Answers1

6

Try this way:

NSDate *today=[NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components=[[NSDateComponents alloc] init];
components.day=45;
NSDate *targetDate =[calendar dateByAddingComponents:components toDate:today options: 0];
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140