0

Contrary to what I expected setting the weekOfMonth property from an NSDateComponents object does not have an effect on weekOfYear...

NSDateComponents *iterativeComponents = [calendar components:   NSYearCalendarUnit|
                                                                        NSMonthCalendarUnit|
                                                                        NSWeekOfYearCalendarUnit|
                                                                        NSWeekOfMonthCalendarUnit|
                                                                        NSWeekdayCalendarUnit
                                                            fromDate:referenceDate];

for (int j = 4; j > -1; j--) {
    iterativeComponents.weekOfMonth = j;
    NSDate *dateForWeek = [calendar dateFromComponents:iterativeComponents];
}

Setting the weekOfMonth of iterativeComponents does not change the weekOfYear and leaves me with an inconsistent NSDateComponents object:

<NSDateComponents: 0x9aac9e0>
Calendar Year: 2012
Month: 9
Leap month: no
Week of Year: 36
Week of Month: 3
Weekday: 2

A quick check in the calendar tells me that the third week of September 2009 is the 37th week of the year. The date generated of iterativeComponents is

2012-09-02 22:00:00 +0000

How can I achieve the correct calculation of the weekOfYear property by setting the weekOfMonth?

4

1 に答える 1

0

NSDateComponents要素の単純なコンテナーにすぎません。NSCalendarオブジェクトを計算する のメソッドで魔法が起こりNSDateます。

したがって、コンポーネントを適切な日付に変換してから、に戻しますNSDateComponents

年、月、weekOfMonth から年の週を計算することはできないため (通常、月の 1 週には年の週が 2 つあります)、確認する日 (月曜日など) を選択する必要があります。

于 2013-09-02T10:31:11.950 に答える