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

我有一个如下所示的数组

_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" 

上面的NSArray所有元素都是NSString

如何创建另一个包含特定日期天数的数组

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

使用此算法:

  1. 获取当前年份
  2. 将数组中的每个日期转换为当前年份的日期。 例如,“03/02/1990”变为“03/02/2013”
  3. 如果步骤2的日期在当前日期之前,则将其年份提前一年(即“03/02/2013”​​变为“03/02/2014”)
  4. 使用此问题中的技术,查找从步骤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中获取日期并使用该信息来获取从当前日期到数组中下一个日期的天数差异。

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

试试这段代码。

 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]]; } 

而已! 🙂