假设今天是 2011 年 2 月 21 日(星期一)。这是本月的第三个星期一。如果输入日期,我怎么知道在它之前已经过了多少个星期一?
在 PHP 中,如何知道这个月到今天已经过去了多少个星期一?
假设今天是 2011 年 2 月 21 日(星期一)。这是本月的第三个星期一。如果输入日期,我怎么知道在它之前已经过了多少个星期一?
在 PHP 中,如何知道这个月到今天已经过去了多少个星期一?
$now=time() + 86400;
if (($dow = date('w', $now)) == 0) $dow = 7;
$begin = $now - (86400 * ($dow-1));
echo "Mondays: ".ceil(date('d', $begin) / 7)."<br/>";
为我工作....
编辑:也包括今天的星期一
这听起来像是一个非常简单的除法计算。从当前日期减去上周一过去的天数(例如:周三 = -2),除以 7 并ceil()
四舍五入。
编辑:这将包括当前星期一的数字,返回“3”表示星期一 21 日。
您可以循环遍历直到现在的所有日子并计算星期一:
$firstDate = mktime(0, 0, 0, date("n"), 1, date("Y"));
$now = time();
$mondays = 0;
for ($i = $firstDate; $i < $now; $i = $i + 24*3600) {
if (date("D", $i) == "Mon")
$mondays ++;
}
没有测试过这个脚本
<?php
function mondays_get($month, $stop_if_today = true) {
$timestamp_now = time();
for($a = 1; $a < 32; $a++) {
$day = strlen($a) == 1 ? "0".$a : $a;
$timestamp = strtotime($month . "-$day");
$day_code = date("w", $timestamp);
if($timestamp > $timestamp_now)
break;
if($day_code == 1)
@$mondays++;
}
return $mondays;
}
echo mondays_get('2011-02');
希望这对你有用!我刚把它卷起来。
“当心上述代码中的错误;我只是证明它是正确的,没有尝试过。”
工作正常
试试这个...
//find the most recent monday (doesn't find today if today is Monday though)
$startDate = strtotime( 'last monday' );
//if 'last monday' was not this month, 0 mondays.
//if 'last monday' was this month, count the weeks
$mondays = date( 'm', $startDate ) != date( 'm' )
? 0
: floor( date( 'd', $startDate ) / 7 );
//increment the count if today is a monday (since strtotime didn't find it)
if ( date( 'w' ) == 1 ) $mondays++;
另一种方法是找出今天是星期几,通过某种魔法找到一个月中的第一个这样的日子strtotime()
,然后计算那个和现在之间的差(以周为单位)。请参阅下面的函数,该函数将采用Y-m-d
格式化date()
并返回该月的星期几。
注意:strtotime
需要详细,包括“of”和月份:“2011-02 的第一个星期一”,否则提前一天。当我测试边缘情况时,这让我很伤心。
还添加了一些完全可选的展示辣椒,但我喜欢它。
function nthWeekdayOfMonth($day) {
$dayTS = strtotime($day) ;
$dayOfWeekToday = date('l', $dayTS) ;
$firstOfMonth = date('Y-m', $dayTS) . "-01" ;
$firstOfMonthTS = strtotime($firstOfMonth) ;
$firstWhat = date('Y-m-d', strtotime("first $dayOfWeekToday of $monthYear", $firstOfMonthTS)) ;
$firstWhatTS = strtotime($firstWhat) ;
$diffTS = $dayTS - $firstWhatTS ;
$diffWeeks = $diffTS / (86400 * 7);
$nthWeekdayOfMonth = $diffWeeks + 1;
return $nthWeekdayOfMonth ;
}
$day = date('Y-m-d') ;
$nthWeekdayOfMonth = nthWeekdayOfMonth($day) ;
switch ($nthWeekdayOfMonth) {
case 1:
$inflector = "st" ;
break ;
case 2:
$inflector = "nd" ;
break ;
case 3:
$inflector = "rd" ;
break ;
default:
$inflector = "th" ;
}
$dayTS = strtotime($day) ;
$monthName = date('F', $dayTS) ;
$dayOfWeekToday = date('l', $dayTS) ;
echo "Today is the {$nthWeekdayOfMonth}$inflector $dayOfWeekToday in $monthName" ;