3 回答

TA貢獻1875條經驗 獲得超3個贊
太多的“單行”-所需的變量,以避免與條件重新計算。在我參加會議時扔了一個默認參數(shù)。
function weekOfMonth($when = null) {
if ($when === null) $when = time();
$week = date('W', $when); // note that ISO weeks start on Monday
$firstWeekOfMonth = date('W', strtotime(date('Y-m-01', $when)));
return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);
}
請注意weekOfMonth(strtotime('Oct 31, 2011'));將會返回6; 與OP的預期相反,一些罕見的月份有6周的時間。自從ISO周從星期一開始以來,2017年1月又是6個ISO周的月份-星期日是去年的第一個星期。
對于starshine531,要返回0該月的索引周,請將更改return 1 +為return 0 +或return (int)。
對于Justin Stayton,從星期日開始而不是星期一開始的幾周,我將使用strftime('%U'代替date('W',如下所示:
function weekOfMonth($when = null) {
if ($when === null) $when = time();
$week = strftime('%U', $when); // weeks start on Sunday
$firstWeekOfMonth = strftime('%U', strtotime(date('Y-m-01', $when)));
return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);
}
對于此版本,2017-04-30現(xiàn)在在四月的第六周,而2017-01-31現(xiàn)在在第五周。

TA貢獻1795條經驗 獲得超7個贊
public function getWeeks($timestamp)
{
$maxday = date("t",$timestamp);
$thismonth = getdate($timestamp);
$timeStamp = mktime(0,0,0,$thismonth['mon'],1,$thismonth['year']); //Create time stamp of the first day from the give date.
$startday = date('w',$timeStamp); //get first day of the given month
$day = $thismonth['mday'];
$weeks = 0;
$week_num = 0;
for ($i=0; $i<($maxday+$startday); $i++) {
if(($i % 7) == 0){
$weeks++;
}
if($day == ($i - $startday + 1)){
$week_num = $weeks;
}
}
return $week_num;
}
您好,我整天都在努力嘗試找出此代碼,我終于明白了,所以我想我將與大家分享。
您需要做的就是在函數(shù)中添加一個時間戳,它會將星期幾返回給您。
謝謝
- 3 回答
- 0 關注
- 522 瀏覽
添加回答
舉報