【问题标题】:Get next year from the current NSDate?从当前的 NSDate 获取明年?
【发布时间】:2011-05-25 03:47:50
【问题描述】:

我有一个日历应用程序,我想从当前日期 (NSDate) 获取下一年。

我该怎么做?

【问题讨论】:

  • 只需从当前日期获取年份并添加一个。哪一部分你不知道怎么做?

标签: ios cocoa-touch nsdate nsdateformatter


【解决方案1】:

您可以让NSDateComponents 完成所有计算闰年和闰秒的繁重工作:

NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setYear:1];
NSDate *nextYear = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];

【讨论】:

    【解决方案2】:

    正如 VdesmedT 提到的,您可以使用 dateByAddingTimeInterval 并添加一年的秒数。但更准确地说,您可以执行以下操作:

    NSDate *today = [NSDate date]; // get the current date
    NSCalendar* cal = [NSCalendar currentCalendar]; // get current calender
    NSDateComponents* dateOnlyToday = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) fromDate:today];
    [dateOnlyToday setYear:([dateOnlyToday year] + 1)];
    NSDate *nextYear = [cal dateFromComponents:dateOnlyToday];

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      斯威夫特 4:

      let calendar = Calendar.current
      let newDate = calendar.date(byAdding: .year, value: 1, to: Date())
      

      【讨论】:

        【解决方案4】:

        这是我的版本:很快。

        let calendar = NSCalendar.currentCalendar()
        let newDate = calendar.dateByAddingUnit(.Year, value: 1, toDate: NSDate(), options: NSCalendarOptions.MatchNextTime)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-03
          相关资源
          最近更新 更多