3

夏時間、うるう年などを考慮した 30 日の配列を作成しようとしています。現在、日の配列を作成するジェネレーターがありますが、特別な時間の変更と年を考慮していません。月が変わります。これが私の現在のコードです:

    NSMutableArray* dates = [[NSMutableArray alloc] init];
    int numberOfDays=30;
    NSDate *startDate=[NSDate date];
    NSDate *tempDate=[startDate copy];
    for (int i=0;i<numberOfDays;i++) {
        NSLog(@"%@",tempDate.description);
        tempDate=[tempDate dateByAddingTimeInterval:(60*60*24)];
        [dates addObject:tempDate.description];
    }

    NSLog(@"%@",dates);

今日の日付から始まる次の 30 日を取得するためにカレンダーをループするジェネレータを作成する最良の方法は何ですか。配列には今日の日付と次の 29 日が含まれている必要があります。私の現在のコードは私が言ったように動作しますが、完全に正確ではありません。ありがとう

4

2 に答える 2

9

あなたはほとんどそれを手に入れました。いくつかの変更のみ:

int numberOfDays=30;

NSDate *startDate=[NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *offset = [[NSDateComponents alloc] init];
NSMutableArray* dates = [NSMutableArray arrayWithObject:startDate];

for (int i = 1; i < numberOfDays; i++) {
  [offset setDay:i];
  NSDate *nextDay = [calendar dateByAddingComponents:offset toDate:startDate options:0];
  [dates addObject:nextDay];
}
[offset release];

NSLog(@"%@",dates);

これにより、オブジェクトの配列が作成されNSDateます。私のマシンでは、次のログが記録されます。

EmptyFoundation[4302:903] (
    "2011-02-16 16:16:26 -0800",
    "2011-02-17 16:16:26 -0800",
    "2011-02-18 16:16:26 -0800",
    "2011-02-19 16:16:26 -0800",
    "2011-02-20 16:16:26 -0800",
    "2011-02-21 16:16:26 -0800",
    "2011-02-22 16:16:26 -0800",
    "2011-02-23 16:16:26 -0800",
    "2011-02-24 16:16:26 -0800",
    "2011-02-25 16:16:26 -0800",
    "2011-02-26 16:16:26 -0800",
    "2011-02-27 16:16:26 -0800",
    "2011-02-28 16:16:26 -0800",
    "2011-03-01 16:16:26 -0800",
    "2011-03-02 16:16:26 -0800",
    "2011-03-03 16:16:26 -0800",
    "2011-03-04 16:16:26 -0800",
    "2011-03-05 16:16:26 -0800",
    "2011-03-06 16:16:26 -0800",
    "2011-03-07 16:16:26 -0800",
    "2011-03-08 16:16:26 -0800",
    "2011-03-09 16:16:26 -0800",
    "2011-03-10 16:16:26 -0800",
    "2011-03-11 16:16:26 -0800",
    "2011-03-12 16:16:26 -0800",
    "2011-03-13 16:16:26 -0700",
    "2011-03-14 16:16:26 -0700",
    "2011-03-15 16:16:26 -0700",
    "2011-03-16 16:16:26 -0700",
    "2011-03-17 16:16:26 -0700"
)

タイムゾーン オフセットが 3 月 13 日に から-0800にどのように変化するかに注意してください-0700。それがサマータイムです。:)

于 2011-02-17T00:14:11.020 に答える
1

上記の補足のコード:

- (NSRange) daysInMonth:(NSDate*)date {

    NSCalendar* cal = [NSCalendar currentCalendar];
    NSDateComponents *comps = [cal components:(NSYearCalendarUnit|NSMonthCalendarUnit) 
                                     fromDate:(date != nil) ? date: self.currentMonth];

    NSRange range = [cal rangeOfUnit:NSDayCalendarUnit
                              inUnit:NSMonthCalendarUnit
                             forDate:[cal dateFromComponents:comps]];

    return range;
}
于 2011-02-17T00:19:14.817 に答える