猿问

PHP获取每月的星期数

所以我有一个脚本,可以返回特定月份和年份中的星期数。我该如何从该月开始的某一天,确定是该月的第1,2,3,4或5周的一部分?



慕的地6264312
浏览 504回答 3
3回答

翻过高山走不出你

太多的“单行”-所需的变量,以避免与条件重新计算。在我参加会议时扔了一个默认参数。function weekOfMonth($when = null) {&nbsp; &nbsp; if ($when === null) $when = time();&nbsp; &nbsp; $week = date('W', $when); // note that ISO weeks start on Monday&nbsp; &nbsp; $firstWeekOfMonth = date('W', strtotime(date('Y-m-01', $when)));&nbsp; &nbsp; 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) {&nbsp; &nbsp; if ($when === null) $when = time();&nbsp; &nbsp; $week = strftime('%U', $when); // weeks start on Sunday&nbsp; &nbsp; $firstWeekOfMonth = strftime('%U', strtotime(date('Y-m-01', $when)));&nbsp; &nbsp; return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);}对于此版本,2017-04-30现在在四月的第六周,而2017-01-31现在在第五周。

一只萌萌小番薯

public function getWeeks($timestamp){&nbsp; &nbsp; $maxday&nbsp; &nbsp; = date("t",$timestamp);&nbsp; &nbsp; $thismonth = getdate($timestamp);&nbsp; &nbsp; $timeStamp = mktime(0,0,0,$thismonth['mon'],1,$thismonth['year']);&nbsp; &nbsp; //Create time stamp of the first day from the give date.&nbsp; &nbsp; $startday&nbsp; = date('w',$timeStamp);&nbsp; &nbsp; //get first day of the given month&nbsp; &nbsp; $day = $thismonth['mday'];&nbsp; &nbsp; $weeks = 0;&nbsp; &nbsp; $week_num = 0;&nbsp; &nbsp; for ($i=0; $i<($maxday+$startday); $i++) {&nbsp; &nbsp; &nbsp; &nbsp; if(($i % 7) == 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $weeks++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if($day == ($i - $startday + 1)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $week_num = $weeks;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; return $week_num;}您好,我整天都在努力尝试找出此代码,我终于明白了,所以我想我将与大家分享。您需要做的就是在函数中添加一个时间戳,它会将星期几返回给您。谢谢
随时随地看视频慕课网APP
我要回答