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

このアルゴリズムを使用します。

  1. 現在の年を取得する
  2. 配列の各日付を現在の年の日付に変換します。たとえば、「03/02/1990」は「03/02/2013」になります。
  3. 手順2の日付が現在の日付より前の場合は、その年を1つ進めます(つまり、「2013年3月2日」は「2014年3月2日」になります)。
  4. この質問の手法を使用して、ステップ3からの日付までの日数を見つけます。これは1年の日数よりも少なくなります。
于 2013-03-12T10:19:06.917 に答える
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 に答える
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 に答える