【问题标题】:adding current and future dates to an array将当前和未来日期添加到数组
【发布时间】:2013-02-22 17:07:04
【问题描述】:

我正在创建一个自定义类型的日历,并且我正在尝试查看是否可以将日期存储在一个数组中而无需静态分配每个日期。例如,数组中的第一个日期将是它第一次创建的日期,它将保存下周让我们说到数组中的相关索引中。

NSMutableArray *thisWeek = [today, tomorrow, sunday(Feb 24), monday (Feb 25), etc];

存储未来日期的最佳方式是什么?

【问题讨论】:

  • 没有得到你的问题。但是您可以将日期存储在数组中,这没有问题。
  • 我的问题是如何将一周的日期存储在一个数组中,第一个日期是今天?

标签: objective-c cocoa nsmutablearray nsdate


【解决方案1】:
NSMutableArray *days = [[NSMutableArray alloc] init]; 
NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *tempCop = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
                                   fromDate:[NSDate date]];
NSDate *today = [cal dateFromComponents:tempCop];

for (int i = 0; i < 8; i++) 
{
    NSDateComponents *comps = [[NSDateComponents alloc]init];
    [comps setDay:i];
    [days addObject:[cal dateByAddingComponents:comps toDate:today options:0]];     
}

【讨论】:

  • 没有时间有什么办法保存?
  • 使用 - (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)date 从当前日期创建组件。将单位标志传递为 (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)。
  • 您能否将其更新为您的答案。我在弄清楚如何添加它时遇到了一点麻烦。抱歉。
【解决方案2】:
NSMutableArray *days;
days = [[NSMutableArray alloc] init]; 

NSDate *todayDate = [NSDate Date];
[days addObject:todayDate]; 

for (int i = 1; i <= 6; i++) 
{
    NSDate *newDate = [[NSDate date] dateByAddingTimeInterval:60*60*24*i];

    [days addObject:newDate];

} 

这样可以在数组中添加天数。

【讨论】:

    【解决方案3】:

    查看 NSDate 文档 (link) 中的 dateByAddingTimeInterval:。它使您可以在日期中添加给定的秒数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多