3 回答
TA贡献1875条经验 获得超3个赞
太多的“单行”-所需的变量,以避免与条件重新计算。在我参加会议时扔了一个默认参数。
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现在在四月的第六周,而2017-01-31现在在第五周。
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;
}
您好,我整天都在努力尝试找出此代码,我终于明白了,所以我想我将与大家分享。
您需要做的就是在函数中添加一个时间戳,它会将星期几返回给您。
谢谢
- 3 回答
- 0 关注
- 503 浏览
添加回答
举报