【问题标题】:Calculate Year From current NSDate从当前 NSDate 计算年份
【发布时间】:2012-06-13 14:07:16
【问题描述】:

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

  1. 下一年或结束年 年结束的日期(如 2012 年 12 月 31 日)。
  2. 下一个或年末月份(最后一个日期月份)。
  3. 下一年或结束年份(最后日期年份或下一年)。

应该是 NSDate 格式。希望你能明白我的意思。

【问题讨论】:

  • 能否请您重新表述您的问题?目前很难理解。您是否要检索给定年份的最后一天的日期(例如,对于输入 14-06-2012,您想要结果 31-12-2012)?
  • 很好。让我澄清一下。如果今天的日期是 2012 年 6 月 13 日,那么从今天开始一年后的最后一个日期是什么。
  • “最后日期”对我来说仍然不清楚。您是指作为输入的年份之后一年中最后一天的日期吗?那么如果输入是 14-06-2012,那么输出应该是 31-12-2013?

标签: iphone objective-c nsdate nscalendar nsdatecomponents


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    你可以用这个:

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

    【讨论】:

    • 这是什么 MyTargetDateObject。是 NSDate 实例吗?
    • 我认为这不能满足 OP 的要求。我相信他正试图找到给定日期的一年中的最后一个日期,但您的代码只会返回相同的日期并添加年份。
    • 是的!这就是我在上面的代码中测试的结果,但它给出了明年的相同日期。正如我提到的,我想要一年中的最后一个日期。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多