-1

I want to calculate the year from current NSDate. Suppose my current date 14-06-2012 so, what would be last date after end of year. (In simple way I can explain you that, if I have date 01-01-2012 then after end of year I would get 31-12-2012). So, how do I calculate year form current date. Following output I expect for my project:

  1. Next or End year Date where year end (Like 31-12-2012).
  2. Next or end year month (Last date month).
  3. Next or end year (Last date year or next year).

It Should be NSDate format. Hope you would able to understand my point.

FreeAsInBeer
  • 12,937
  • 5
  • 50
  • 82
iMash
  • 1,178
  • 1
  • 12
  • 33
  • Could you please rephrase your question? It is quite difficult to understand at the moment. Do you want to retrieve the date of the last day of a given year (so e.g. for the input 14-06-2012 you want the result 31-12-2012)? – Tim Jun 13 '12 at 15:20
  • Fine. Let me clarify. If today date is 13-06-2012 then what would be the last date after completion of one year from today date. – iMash Jun 13 '12 at 15:23
  • "Last date" is still not clear to me. Do you mean the date of the last day of the year following the year given as input? So if the input is 14-06-2012, the output should be 31-12-2013? – Tim Jun 13 '12 at 15:31

2 Answers2

3
NSDate *today = [NSDate date]; 
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:(NSYearCalendarUnit) fromDate:today];

[comps setDay:31]; // last day of year is always the same
[comps setMonth:12];

NSInteger year = [comps year]; // the current year
NSDate *lastDayOfYear = [gregorian dateFromComponents:comps]; // the last day of the year
thelaws
  • 7,991
  • 6
  • 35
  • 54
0

You can use this:

NSDate *now = [NSDate date];
NSDateComponents *dc = [[NSDateComponents alloc] init];
[dc setYear:1];
NSDate *targetDateObject = [[NSCalendar currentCalendar] dateByAddingComponents:dc toDate:now options:0];
[dc release];
FreeAsInBeer
  • 12,937
  • 5
  • 50
  • 82
Nuzhat Zari
  • 3,398
  • 2
  • 24
  • 36
  • What's this MyTargetDateObject. Is it NSDate instance? – iMash Jun 13 '12 at 14:11
  • I don't think this achieves the OP's request. I believe he is trying to find the very last date of the year given a date, but your code would simply return the same date with an added year. – FreeAsInBeer Jun 13 '12 at 14:20
  • Yes! this is what happening I tested above code, but it's giving the same date for next year. As I mentioned I want the last date of year. – iMash Jun 13 '12 at 14:39