【问题标题】:How to get future dates如何获得未来的日期
【发布时间】:2011-09-23 13:02:48
【问题描述】:

如何使用 NSDateComponents 获取周三和周五的一些未来日期?答案将不胜感激。提前致谢。

【问题讨论】:

标签: iphone objective-c xcode nsdate nsdateformatter


【解决方案1】:

如果您希望它完全防弹,这实际上是一个有点棘手的问题。以下是我的做法:

NSInteger wednesday = 4; // Wed is the 4th day of the week (Sunday is 1)
NSInteger friday = 6;

NSDate *start = ...; // your starting date
NSDateComponents *components = [[NSDateComponents alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

for (int i = 0; i < 100; ++i) {
  [components setDay:i];
  NSDate *target = [gregorian dateByAddingComponents:components toDate:start options:0];
  NSDateComponents *targetComponents = [gregorian components:NSUIntegerMax fromDate:target];
  if ([targetComponents weekday] == wednesday || [targetComponents weekday] == friday) {
    NSLog(@"found wed/fri on %d-%d-%d", [targetComponents month], [targetComponents day], [targetComponents year]);
  }
}

[gregorian release];
[components release];

【讨论】:

    【解决方案2】:

    要获得正确的星期几,您必须创建一个合适的 NSCalendar 实例,使用 dateFromComponents: 创建一个 NSDate 对象,然后使用 components:fromDate: 检索工作日。

    【讨论】:

      【解决方案3】:

      如果您有具体工作日(例如星期三)的 NSDate 实例,则可以使用以下代码获取新的未来日期:

      NSDate *yourDate = ...
      NSDateComponents* components = [[NSDateComponents alloc] init];
      components.week = weeks;
      NSDate* futureDate = [[NSCalendar reCurrentCalendar] dateByAddingComponents:components toDate:yourDate options:0];
      [components release];
      

      附:同意布赖恩的观点,在询问之前尝试进行研究。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-19
        • 2015-09-13
        • 2015-10-17
        • 1970-01-01
        相关资源
        最近更新 更多