从当前的NSDate计算年份

时间:2012-06-13 14:07:17

标签: iphone objective-c nsdate nscalendar nsdatecomponents

我想从当前的NSDate计算年份。假设我当前的日期 14-06-2012 那么,年底之后的最后日期是什么。 (简单地说,我可以解释一下,如果我有约会 01-01-2012 那么在年底之后我会得到 31-12-2012 )。那么,我该如何计算年份当前日期。 以下输出我希望我的项目:

  
      
  1. 下一年或结束年年终的日期(如31-12-2012)。
  2.   
  3. 下一个或结束年月(上个月日期)。
  4.   
  5. 下一年或结束年(上一年或明年)。
  6.   

它应该是NSDate格式。希望你能理解我的观点。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用:

NSDate *now = [NSDate date];
NSDateComponents *dc = [[NSDateComponents alloc] init];
[dc setYear:1];
NSDate *targetDateObject = [[NSCalendar currentCalendar] dateByAddingComponents:dc toDate:now options:0];
[dc release];
相关问题