【问题标题】:How to add a number of weeks to an NSDate?如何在 NSDate 中添加几周?
【发布时间】:2015-03-10 22:37:17
【问题描述】:

我过去曾使用以下函数将使用NSDateComponents 的特定时间间隔添加到现有日期。

(NSDate *)dateByAddingComponents:(NSDateComponents *)comps
                          toDate:(NSDate *)date
                         options:(NSCalendarOptions)opts

从 iOS8 开始,不推荐使用 NSDateComponents 的周值,这意味着我无法实现我想做的事情:通过在给定的 NSDate 上添加一定数量的周数来生成新的 NSDate

任何帮助将不胜感激。

【问题讨论】:

  • 你试过weekOfYear吗?

标签: ios objective-c ios8 nsdate nsdatecomponents


【解决方案1】:

更新:正如 Zaph 在他的回答中所说,Apple 实际上建议使用 weekOfYearweekOfMonth 而不是我提供的答案。详情请查看 Zaph 的回答。


您可能很快就会意识到自己想多了,但是即使周值已被弃用,您也可以通过以下方法将特定周数添加到日期,例如:

NSDateComponents *comp = [NSDateComponents new];
int numberOfDaysInAWeek = 7;
int weeks = 3; // <-- this example adds 3 weeks
comp.day = weeks * numberOfDaysInAWeek;

NSDate *date = [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:date options:0];

【讨论】:

  • 没问题。它发生了:)
  • 对不起,但这个答案可能是错误的,因为它假设每周正好有 7 天。 @Zaph 的答案更安全。
  • @rmaddy 无需道歉。我不知道有什么情况下周不正好有 7 天(也许是夏令时?),我也没有意识到存在 weekOfYear 或 weekOfMonth 属性;但如果 Apple 说要改用 weekOfYear 或 weekOfMonth,那就应该使用它。我将对此进行更多研究以找出 weekOfYear 和 weekOfMonth 之间的区别,然后进行相应更新。谢谢!
  • @LyndseyScott 诚然,我不知道使用“days * 7”会产生与使用“weekOfYear”不同的结果的确切情况,但会想到夏令时和闰年(或闰秒) .
  • 当使用weekOfMonthweekOfYear 对日期进行加减运算时,它们的工作方式相同。它们的不同之处在于它们用于获取周数。 ——
【解决方案2】:

您可以使用以下方法在 NSDate 上添加类别:

- (NSDate *) addWeeks:(NSInteger)weeks
{
    NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components=[[NSDateComponents alloc] init];
    components.day = weeks * 7;

    return [gregorian dateByAddingComponents:components toDate:self options:0];
}

【讨论】:

【解决方案3】:

只需使用weekOfYear:

NSDateComponentsweek 的 Apple 文档:

弃用声明
请改用 weekOfYear 或 weekOfMonth,具体取决于您的意图。

NSDate *date = [NSDate date];
NSDateComponents *comp = [NSDateComponents new];
comp.weekOfYear = 3;
NSDate *date1 = [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:date options:0];
NSLog(@"date:  %@", date);
NSLog(@"date1: %@", date1);

输出:

日期:2015-01-13 04:06:26 +0000 日期1:2015-02-03 04:06:26 +0000

如果您使用week,您会收到以下警告:

'week' 已弃用:首先在 ... 中弃用 - 使用 weekOfMonth 或 weekOfYear,具体取决于您的意思

当使用weekOfMonthweekOfYear 作为增量时,它们的工作方式相同。它们的不同之处在于,当它们用于获取周数时,您将获得范围为 6 的月份中的一周或范围为 53 的一年中的一周。

【讨论】:

    【解决方案4】:

    我更喜欢使用 dateByAddingUnit。更直观

    return [NSDate[[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitMonth value:3 toDate:toDate options:0];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 2018-02-06
      相关资源
      最近更新 更多