3

次の金曜日の日付を返す関数を作成したいのですが、それを行う方法がわかりません。誰かが私に良いヒントを持っていますか?

4

5 に答える 5

2

たとえば、NSDate を使用して現在の日付を取得し、NSCalendar から 'components>fromDate:' を使用して NSDateComponents を取得し、次の金曜日までの時差を追加して新しい NSDate を作成すると、Bob's はあなたのおじです。

于 2010-05-22T00:26:06.943 に答える
2

グレゴリオ暦で次の5つの日曜日を取得するための私の実用的なソリューションは次のとおりです。

self.nextBeginDates = [NSMutableArray array];

NSDateComponents *weekdayComponents = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int currentWeekday = [weekdayComponents weekday]; //[1;7] ... 1 is sunday, 7 is saturday in gregorian calendar

NSDateComponents *comp = [[NSDateComponents alloc] init];
[comp setDay:8 - currentWeekday];   // add some days so it will become sunday

// build weeks array
int weeksCount = 5;
for (int i = 0; i < weeksCount; i++) {
    [comp setWeek:i];   // add weeks

    [nextBeginDates addObject:[[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:[NSDate date] options:0]];
}
[comp release];
于 2011-09-21T08:49:53.807 に答える
1

これはうまくいくはずです

+ (NSDate *) dateForNextWeekday: (NSInteger)weekday {

NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];

// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit
                                                   fromDate:today];

/*
 Add components to get to the weekday we want
 */
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
NSInteger dif = weekday-weekdayComponents.weekday;
if (dif<=0) dif += 7;
[componentsToSubtract setDay:dif];

NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract
                                                     toDate:today options:0];

return beginningOfWeek;

}

于 2013-02-12T14:42:33.360 に答える
-2

これが私の解決策です。警告するために、土曜日は表示される前の金曜日です。みんなで乾杯

NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:today];
int weekday = [weekdayComponents weekday];


int iOffsetToFryday = -weekday + 6;
weekdayComponents.weekday = iOffsetToFryday;

NSDate *nextFriday = [[NSCalendar currentCalendar] dateByAddingComponents:weekdayComponents toDate:today options:0];
于 2010-05-24T20:13:36.000 に答える