【问题标题】:Get last tuesday in month ios获取本月最后一个星期二 ios
【发布时间】:2016-06-29 08:31:02
【问题描述】:

可以通过 NSDateComponents 获取当月最后一个工作日吗?例如:一个月的最后一个星期一或一个月的最后一个星期五。等等

【问题讨论】:

  • 我不这么认为,但是写一个方法很容易。算法类似于:given month m, d = lastDayInMonth(m), while(notWeekday(d)) d--;

标签: ios objective-c nsdate nsdatecomponents


【解决方案1】:

只是另一种解决方法。找到下个月的第一天,然后向后搜索星期二。

let calendar = NSCalendar.currentCalendar()
let today = NSDate()
let components = calendar.components([.Year, .Month], fromDate: today)
components.month += 1

// If today is 2016-07-12 then nextMonth will be the 
// first day of the next month: 2016-08-01
if let nextMonth = calendar.dateFromComponents(components) {
    // Search backwards for weekday = Tuesday
    let options: NSCalendarOptions = [.MatchPreviousTimePreservingSmallerUnits, .SearchBackwards]
    calendar.nextDateAfterDate(nextMonth, matchingUnit: .Weekday, value: 3, options: options)
}

【讨论】:

    【解决方案2】:

    这里有一个解决方案;我认为经过测试,并且相当强大。 我们将让 NSCalendar 遍历整个月,一次一天,并提取所有匹配的工作日作为 NSDates。然后您可以回答诸如“本月的第三个星期三”之类的问题

    我相信 cmets 很清楚正在发生的事情以及原因。 如果您需要进一步说明,我很乐意这样做。

    //What weekday are we interested in? 1 = Sunday . . . 7 = Saturday
    NSInteger targetWeekday = 1;
    
    //Using this methodology, GMT timezone is important to set
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    calendar.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    
    //set the components to the first of the current month
    NSDateComponents *startComponents = [calendar components:NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
    startComponents.day = 1;
    
    //the enumeration starts "afterDate", so shift the start back one day (86400 seconds) to include the 1st of the month
    NSDate *startDate = [[calendar dateFromComponents:startComponents] dateByAddingTimeInterval:-86400];
    
    //the enumeration searches for a match; we'll match at the midnight hour and find every occurance of midnight
    NSDateComponents *dayByDay = [[NSDateComponents alloc] init];
    dayByDay.hour = 0;
    
    //I've opted to put all matching weekdays of the month into an array, so you can find any instance easily
    __block NSMutableArray *foundDates = [NSMutableArray arrayWithCapacity:5];
    [calendar enumerateDatesStartingAfterDate:startDate
                           matchingComponents:dayByDay
                                      options:NSCalendarMatchPreviousTimePreservingSmallerUnits
                                   usingBlock:^(NSDate *date, BOOL exactMatch, BOOL *stop){
                                       NSDateComponents *thisComponents = [calendar components:NSCalendarUnitMonth | NSCalendarUnitWeekday fromDate:date];
                                       //as long as the month stays the same... (or the year, if you wanted to)
                                       if (thisComponents.month == startComponents.month) {
    
                                           //does this date match our target weekday search?
                                           if (thisComponents.weekday == targetWeekday) {
    
                                               //then add it to our result array
                                               [foundDates addObject:date];
                                           }
    
                                       //once the month has changed, we're done
                                       } else {
                                           *stop = YES;
                                       }
                                   }];
    
    //Now, with our search result array, we can find the 1st, last, or any specific occurance of that weekday on that month
    NSLog(@"Found these: %@", foundDates);
    

    所以,如果你只想要最后一个,那么只需使用 [foundDates lastObject]

    【讨论】:

    • 太好了,很高兴它有帮助:)
    【解决方案3】:

    试试这个代码。这对我有用。

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
    int weekday = [comps weekday];
    int lastTues;
    int lastSatDay;
    if (weekday==1) {
        lastTues=5;
        lastSatDay=1;
    }
    else if (weekday==2)
    {
        lastTues=6;
        lastSatDay=2;
    }
    else if (weekday==3)
    {
        lastTues=7;
        lastSatDay=3;
    }
    else if (weekday==4)
    {
        lastTues=1;
        lastSatDay=4;
    }
    else if (weekday==5)
    {
        lastTues=2;
        lastSatDay=5;
    }
    else if (weekday==6)
    {
        lastTues=3;
        lastSatDay=6;
    }
    else if (weekday==7)
    {
        lastTues=4;
        lastSatDay=7;
    }
    
    NSDate *lastTuesDay = [[NSDate date] addTimeInterval:-3600*24*(lastTues)];
    NSDate *lastSaturday = [[NSDate date] addTimeInterval:-3600*24*(lastSatDay)];
    

    【讨论】:

    • 如果我想知道上周六我应该写什么。 @stanly 摩西
    • 查看更新后的代码...如果它回答则接受,否则返回,我将帮助您解决问题。
    • 这是给即将到来的周六而不是给上周六@Stanly Moses
    • 给予来是什么意思?
    • 上周六的显示是»»»» 2016-07-01 09:17:21 +0000
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多