2

我有如下数组

_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
)
4

3 回答 3

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 中的日期并使用该信息来获取从当前日期到数组中下一个日期的天数差异。

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

于 2013-03-12T10:14:47.123 回答
3

使用这个算法:

  1. 获取当前年份
  2. 将数组中的每个日期转换为当年的日期。例如,“03/02/1990”变为“03/02/2013”
  3. 如果步骤 2 中的日期早于当前日期,则将其年份提前一年(即“03/02/2013”​​变为“03/02/2014”)
  4. 使用this question中的技术,找到从第3步到日期的天数。它将小于一年中的天数。
于 2013-03-12T10:19:06.917 回答
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]];
}

而已!:)

于 2013-03-12T10:19:41.580 回答