Get the last weekday of a month

混江龙づ霸主 提交于 2019-12-25 00:29:06

问题


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.

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?


回答1:


Had the same need recently, and the best I could come up with is the following, which is meant to be run every day to check if the current day is the last weekday of the current month:

<?php
$d = new DateObject('first day of this month', date_default_timezone());
$d->modify("+15 days");
$d->modify("first day of next month -1 weekday");
$last = date_format($d, 'd');
$today = new DateObject('today', date_default_timezone());
$today = date_format($today, 'd');
if ($today == $last) {
  //bingo
}
?>

I have been testing and so far couldn't find an example where this fails. The reason for doing the modify("+15 days") in the middle is to be sure we are calling "next month" with a starting date that is not in the edge between two months, case where I believe this could fail.

Leaving the code shown before apparently covers all cases.




回答2:


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;
}


来源:https://stackoverflow.com/questions/24075466/get-the-last-weekday-of-a-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!