我希望获得从2012-01-01到2012-12-31给定的两个日期之间的周数。这些周数应该正好在上述范围内。请问如何实现这一目标。
我希望获得从2012-01-01到2012-12-31给定的两个日期之间的周数。这些周数应该正好在上述范围内。请问如何实现这一目标。
类似这样的代码应该可以正常工作:
<?php
$startDateUnix = strtotime('2012-01-01');
$endDateUnix = strtotime('2013-01-01');
$currentDateUnix = $startDateUnix;
$weekNumbers = array();
while ($currentDateUnix < $endDateUnix) {
$weekNumbers[] = date('W', $currentDateUnix);
$currentDateUnix = strtotime('+1 week', $currentDateUnix);
}
print_r($weekNumbers);
?>
DEMO.
Output:
Array
(
[0] => 52
[1] => 01
[2] => 02
.........
[51] => 51
[52] => 52
)
$start = '2012-01-01';
$end = '2012-12-31';
$dates = range(strtotime($start), strtotime($end),604800);
$weeks = array_map(function($v){return date('W', $v);}, $dates); // Requires PHP 5.3+
print_r($weeks);
$start = '2012-12-15'; $end = '2013-03-21';
会输出一个范围在 50
和 12
之间的结果,这是错误的。 - h2ooooooo我认为你想要类似以下使用DateTime的内容:
$first_date = new DateTime();
$last_date = new DateTime('-50 weeks');
$days_array = array();
foreach(new DatePeriod($first_date, new DateInterval('P1D'), $last_date) as $date) {
$days_array[] = $date->format('W');
}
function weeks_between_dates($d1,$d2)
{
$t1 = strtotime($d1);
$t2 = strtotime($d2);
$out = array();
while ($now <= $t2) {
$out[] = date('W', $t1);
$t1 = strtotime('+1 week', $t1);
}
return $out;
}
print_r( weeks_between_dates('2015-01-01','2015-12-31') ); // 01..53
print_r( weeks_between_dates('2016-01-01','2016-12-31') ); // 01..52
做类似这样的事情:
[已删除]
编辑
<?php
for($w = strtotime($start_date); $w <= strtotime($end_date); $w += 7 * 24 * 3600)
{
echo date("W", $w) . '<br />';
}
?>