获取一个月的最后一个工作日 [英] Get the last weekday of a month

查看:101
本文介绍了获取一个月的最后一个工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取给定月份的最后一个工作日.我遇到了这个简单的答案,了解如何获得第一个/第二个/...工作日效果很好.

I want to get the last weekday of a given month. I've come across this simple answer on how to get the 1st/2nd/... weekday which works well.

问题是:如何获得给定月份的最后一个工作日?不是每个月都只有4个星期天,那么我是不是要计算这个月的星期天数呢,还是有更优雅的方法呢?

The question is: How to get the last weekday of a given month? Not every month has only 4 Sundays, so do I have to count the number of Sundays of the month, or is there a more elegant way to do this?

推荐答案

我终于想出了以下解决方案.为方便起见,我使用 NSDate-Extensions.dayOfWeek 代表公历中的星期日 (1) 至星期六 (7):

I finally came up with the following solution. I'm using NSDate-Extensions for convenience. dayOfWeek stands for Sunday (1) till Saturday (7) in the Gregorian calendar:

- (NSDate *)dateOfLastDayOfWeek:(NSInteger)dayOfWeek afterDate:(NSDate *)date
{
    // Determine the date one month after the given date
    date = [date dateByAddingMonths:1];

    // Set the first day of this month
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.year = date.year;
    dateComponents.month = date.month;
    dateComponents.day = 1;

    // Get the date and then the weekday of this first day of the month
    NSDate *tempDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *firstDayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:tempDate];
    NSInteger weekday = firstDayComponents.weekday;

    // Determine how many days we have to go back to the desired weekday
    NSInteger daysBeforeThe1stOfNextMonth = (weekday + 7) - dayOfWeek;
    if (daysBeforeThe1stOfNextMonth > 7)
    {
        daysBeforeThe1stOfNextMonth -= 7;
    }

    NSDate *dateOfLastDayOfWeek = [tempDate dateBySubtractingDays:daysBeforeThe1stOfNextMonth];
    return dateOfLastDayOfWeek;
}

这篇关于获取一个月的最后一个工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆