0

私はこの 13、27、29 のような文字列を持っており、以下のようにそれらを日付オブジェクトに分割したいと考えています。

mayString = [mayString componentsSeparatedByString:@","];

次に、これらの日のうち、13 日、27 日、または 29 日が今日の日付に最も近い日を計算できるようにしたいと考えています。上記の日付を使用すると、現在の日付に次に近い日付として 27 になります。

以下を使用して現在の日を取得できますが、これを行うロジックを取得する方法に本当にこだわっていますか?

//Grab current day from sys date
NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init];
[dayFormatter setDateFormat:@"dd"];
NSString *dayString = [dayFormatter stringFromDate:[NSDate date]];

部分的に完成したソリューションがありますが、配列内のどのインデックスが現在の日に最も近いかという正しい結果が得られないようです (sepDates は配列です)

sepDates = [mayString componentsSeparatedByString:@","];

//Day string is todays date i.e 16 (16th)
    NSDate *dayFromString = [dayFormatter dateFromString:dayString];
    NSLog(@"Day from string %@", dayFromString);

    double min = [dayFromString timeIntervalSinceDate:[sepDates objectAtIndex:0]];
    NSLog(@"Min %f", min);

//I then want to calculate which of the dates in the sepDates array at index is closest to todays current day 16

    int minIndex = 0;
    for (int d = 1; d < [sepDates count]; ++d)
    {
        double currentmin = [dayFromString timeIntervalSinceDate:[sepDates objectAtIndex:d]];
        if (currentmin < min) {
            min = currentmin;
            minIndex = d;

            NSLog(@"minIndex = %d", minIndex);

        }
    }
4

3 に答える 3

1
  1. dayString は文字列ではなく、NSInteger である必要があります
  2. 日付を使用して配列を反復処理するときに、すべての文字列を整数に変換します (例: [currentDayString integerValue])

最も近い日を検索する実際のアルゴリズムは、最初の配列を反復処理し、配列と現在の日の値の差の絶対値を見つけることです。これらの違いを別の配列に格納します。2 番目の配列で最小値を見つけます。最小差の位置 (インデックス) は、最初の配列の最も近い日の位置と同じになります。

これは正しいminIndexを与える質問からのコードスニペットです

NSArray *sepDates = @[@"13", @"15", @"27", @"29"];

NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init];
[dayFormatter setDateFormat:@"dd"];
NSString *dayString = [dayFormatter stringFromDate:[NSDate date]];

NSDate *dayFromString = [dayFormatter dateFromString:dayString];
NSLog(@"Day from string %@", dayFromString);


NSInteger min = [[sepDates lastObject] integerValue]; //or set it to some large int
NSLog(@"Min %d", min);
int minIndex = 0;
for (int d = 1; d < [sepDates count]; ++d)
{
    NSInteger currentmin = [sepDates[d] integerValue] - [dayString integerValue];
    NSLog(@"Current min: %d", currentmin);
    //currentmin must be positive since you need next closest day
    if (currentmin > 0 && currentmin < min) {
        min = currentmin;
        minIndex = d;

        NSLog(@"minIndex = %d", minIndex);

    }
}
于 2013-05-16T14:08:07.530 に答える
0

日付を反復し、現在のターゲットから時間を計算し、以前に計算された日付よりも小さい場合、または何も計算されていない場合 (つまり、最初の要素) にその日付を保存します。その結果が答えになります。

于 2013-05-16T14:05:45.620 に答える