我有一个程序来获取一周和一周的开始日期和结束日期。以下是代码。
function getStartAndEndDate($week, $year) {
$dto = new DateTime();
$dto->setISODate($year, $week,0);
$ret['week_start'] = $dto->format('Y-m-d');
$dto->modify('+6 days');
$ret['week_end'] = $dto->format('Y-m-d');
return $ret;
}
$week_array = getStartAndEndDate(5,2017);
print_r($week_array);
这将输出结果为
Array ( [week_start] => 2017-01-29 [week_end] => 2017-02-04 )
但我需要分两周参加。例如,结果应如下
Array ( [week_start] => 2017-01-29 [week_end] => 2017-01-31)
Array ( [week_start] => 2017-02-01 [week_end] => 2017-02-04)
这意味着我需要不同月份的单独值。任何帮助将不胜感激。
答案 0 :(得分:3)
您逐个比较两个日期并使用't'
格式来获取该月的最后一天。请按照description of date()
function 了解有关所有可用格式的详情以及下面的示例。
除非您确实需要可变版本,否则最好使用DateTimeImmutable
代替DateTime
。
function getStartAndEndDate($week, $year)
{
$dto = (new DateTimeImmutable())->setISODate($year, $week, 0);
$weekStart = $dto;
$weekEnd = $dto->modify('+6 days');
$ret = [];
if ($weekStart->format('m') === $weekEnd->format('m')) {
$ret[] = [
'week_start' => $weekStart,
'week_end' => $weekEnd,
];
} else {
$ret[] = [
'week_start' => $weekStart->format('Y-m-d'),
// 't' = the last day of the month.
'week_end' => $weekStart->format('Y-m-t'),
];
$ret[] = [
// The first day of the month.
'week_start' => $weekEnd->format('Y-m-01'),
'week_end' => $weekEnd->format('Y-m-d'),
];
}
return $ret;
}