PHP: getting weekdays numbers of a given month

為{幸葍}努か 提交于 2019-12-14 03:42:45

问题


Given a Month and a weekday, I need to build a function that can retrieve the day number of all Mondays, Tuesdays, Wednesdays, Thursdays and Fridays.

Let's say I give the function this month, September 2012 and weekday number 1. The function should retrieve all the Mondays in September 2012 which are: 3, 10, 17 and 24

Please note that to me weekday number 1 is Monday, number 2 Tuesday, 3 is Wednesday, 4 Thursday and 5 Friday.

So far I've have done: getting the first day of the week given today's date (I post the function below). But I don't know how to follow from here in a simple way, I've been many hours on it and I suspect there's a better way to do it. Can you please show me how?

  function getFirstDayOfWeek($date) {
    $getdate = getdate($date);

    // How many days ahead monday are we?
    switch ( $getdate['wday'] ) {
        case 0: // we are on sunday
            $days = 6;
            break;

        default: // any other day
            $days = $getdate['wday']-1;
            break;
    }

    $seconds = $days*24*60*60;
    $monday = date($getdate[0])-$seconds;

    return $monday;
}

Thanks a ton


回答1:


Not very smart, but would works for you:

// sept. 2012
$month = 9;

// loop through month days
for ($i = 1; $i <= 31; $i++) {

    // given month timestamp
    $timestamp = mktime(0, 0, 0, $month, $i, 2012);

    // to be sure we have not gone to the next month
    if (date("n", $timestamp) == $month) {

        // current day in the loop
        $day = date("N", $timestamp);

        // if this is between 1 to 5, weekdays, 1 = Monday, 5 = Friday
        if ($day == 1 OR $day <= 5) {

            // write it down now
            $days[$day][] = date("j", $timestamp);
        }
    }
}

// to see if it works :)
print_r($days);


来源:https://stackoverflow.com/questions/12511311/php-getting-weekdays-numbers-of-a-given-month

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