首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 計算某月份第 N 個星期幾的日期:使用 NSCalendar 與 NSDateComponents

     編輯:程式設計綜合問答

透過 NSCalendar 取得該月 1 號的星期與天數,計算目標週日的偏移量,即可獲得具體日期。

完整方法

- (NSDate *)dateForWeekday:(NSInteger)weekday weekOfMonth:(NSInteger)week month:(NSInteger)month year:(NSInteger)year {
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *comp = [[NSDateComponents alloc] init];
    comp.year = year; comp.month = month; comp.day = 1;
    NSDate *firstDay = [cal dateFromComponents:comp];

    NSDateComponents *firstComp = [cal components:NSCalendarUnitWeekday fromDate:firstDay];
    NSInteger firstWeekday = firstComp.weekday; // 1=Sun, 2=Mon...

    NSInteger offset;
    if (firstWeekday < weekday) offset = (weekday - firstWeekday) + 7 * (week - 1);
    else if (firstWeekday > weekday) offset = (7 - firstWeekday + weekday) + 7 * (week - 1);
    else offset = 7 * (week - 1);

    NSRange dayRange = [cal rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:firstDay];
    if (offset >= dayRange.length) return nil; // 超過該月天數

    NSDateComponents *addComp = [[NSDateComponents alloc] init];
    addComp.day = offset;
    return [cal dateByAddingComponents:addComp toDate:firstDay options:0];
}

使用範例

// 2024 年 12 月第 3 個星期一
NSDate *date = [self dateForWeekday:2 weekOfMonth:3 month:12 year:2024];

注意

  • weekday 依 NSCalendar 定義:1=週日, 2=週一...7=週六。
  • 若該月第 N 週不存在該週日(如月份天數不足),回傳 nil。
  • iOS 8+ 可改用 NSCalendarUnit 新語法。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved