如何制作包含天数的另一个数组

时间:2013-03-12 10:04:36

标签: iphone ios

我的数组如下所示

 _combinedBirthdates(
"03/12/2013",
"03/12/2013",
"08/13/1990",
"12/09/1989",
"02/06",
"09/08",
"03/02/1990",
"08/22/1989",
"03/02",
"05/13",
"10/16",
"07/08",
"08/31/1990",
"04/14/1992",
"12/15/1905",
"08/14/1989",
"10/07/1987",
"07/25",
"07/17/1989",
"03/24/1987",
"07/28/1988",
"01/21/1990",
"10/13"

以上NSString中的所有元素均为NSArray

如何创建另一个包含特定日期天数的数组 像这样的东西

_newlymadeArray(
"125",
"200",
"50",
"500",
"125",
and so on
)

3 个答案:

答案 0 :(得分:3)

unsigned int unitFlags =  NSDayCalendarUnit;
NSCalendar *currCalendar = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateStyle:NSDateFormatterShortStyle];

NSMutableArray * _newlymadeArray = [[NSMutableArray alloc] init];
for (NSString * str in _combinedBirthdates){

        NSDate * toDate = [dateFormatter dateFromString:str];
        NSDateComponents *daysInfo = [currCalendar components:unitFlags fromDate:[NSDate date]  toDate:toDate  options:0];
        int days = [daysInfo day];
        [_newlymadeArray addObject:[NSString stringWithFormat:@"%d",days]];

    }

您需要遍历第一个数组并在NSDate中获取日期并使用该信息来获取从当前日期到数组中下一个日期的天数差异。

您必须添加必要的检查,这是未经测试的代码。

答案 1 :(得分:3)

使用此算法:

  1. 获取当前年度
  2. 将数组中的每个日期转换为当前年份的日期。例如,“03/02/1990”变为“03/02/2013”​​
  3. 如果第2步的日期在当前日期之前,则将其年份提前一年(即“03/02/2013”​​变为“03/02/2014”)
  4. 使用this question中的技术,查找从第3步开始的天数。它将少于一年中的天数。

答案 2 :(得分:1)

尝试使用此代码快照。

NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
[formatter setDateFormat:@"MM/dd/yyyy"];
NSDate *currentDate = [formatter dateFromString:@"03/12/2013"];
NSTimeInterval srcInterval = [currentDate timeIntervalSince1970];

NSArray *_combinedBirthdates = @[@"03/15/2013", @"05/15/2013"];
NSMutableArray *_newlymadeArray = [NSMutableArray array];
const NSInteger SECONDS_PER_DAY = 60 * 60 * 24;

for (NSString *one in _combinedBirthdates) {
    NSDate *destDate = [formatter dateFromString:one];
    NSTimeInterval destInterval = [destDate timeIntervalSince1970];
    NSInteger diff = (destInterval - srcInterval) / SECONDS_PER_DAY;
    [_newlymadeArray addObject:[NSString stringWithFormat:@"%d", diff]];
}

就是这样! :)