1

私はこのコードを持っています:

- (void) setDataLabel{

for (int k = 0; k<31; k++){

    [[lineSunday objectAtIndex:k] setAlpha:0.00];
    [[arrayDay objectAtIndex:k] setTextColor:[UIColor whiteColor]];
}

NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setYear:2011];
[components setDay:1];
[components setMonth:10];
//NSLog(@"mese:%d", month);
NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *firstDate = [gregorianCalendar dateFromComponents:components];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd"];

for (int i = 0; i < 31; i++) {
    NSTimeInterval seconds = 24*60*60 * i;
    NSDate *date = [NSDate dateWithTimeInterval:seconds sinceDate:firstDate];
    NSDateComponents *weekdayComponents = [gregorianCalendar components:NSWeekdayCalendarUnit fromDate:date];
    int weekday = [weekdayComponents weekday];
    NSString *strDate = [dateFormatter stringFromDate: date];
    [[arrayDay objectAtIndex:i] setText:strDate];
    if (weekday == 1) {
        [[arrayDay objectAtIndex:i] setTextColor:[UIColor redColor]];
        [[lineSunday objectAtIndex:i] setAlpha:1.00];
    }
}

このコードは、月の日を含む31個のラベルを設定し、すべて問題ありませんが、10月に2つの平日が連続する理由がわかりません。例:今年、このコードは月末に次のように記述します。

.... 25 26 27 28 29 30 30

30と30は赤い色ですが、そうではないはずです。

.... 25 26 27 28 29 30 31

そして30だけが赤い色でなければなりません

なぜそれが起こるのですか?

4

1 に答える 1

1

夏時間のせいです。そのループでは、毎日86400秒を追加していますが、1日は25時間になります。

編集:

最善のアプローチは、おそらくループ内の日付オブジェクトを取得するだけで、派手な計算をまったく行わないことです。

- (void) setDataLabel{

    for (int k = 0; k<31; k++){
        [[lineSunday objectAtIndex:k] setAlpha:0.00];
        [[arrayDay objectAtIndex:k] setTextColor:[UIColor whiteColor]];
    }

    NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
    [components setYear:2011];
    [components setMonth:10];
    NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd"];

    for (int i = 0; i < 31; i++) {
        [components setDay:i+1];
        NSDate *date = [gregorianCalendar dateFromComponents:components];
        NSDateComponents *weekdayComponents = [gregorianCalendar components:NSWeekdayCalendarUnit fromDate:date];
        int weekday = [weekdayComponents weekday];
        NSString *strDate = [dateFormatter stringFromDate: date];
        [[arrayDay objectAtIndex:i] setText:strDate];
        if (weekday == 1) {
            [[arrayDay objectAtIndex:i] setTextColor:[UIColor redColor]];
            [[lineSunday objectAtIndex:i] setAlpha:1.00];
        }
    }
    [dateFormatter release];
    [gregorianCalendar release];
    [components release];
}
于 2011-04-20T08:52:50.377 に答える