我得到了一年和一年中的一周'来自外部的来源,我无法改变。我想得到那个具体周的周一和周日的日期。现在我已经得到了以下代码,但看起来相当复杂。
<?php
// simulate the server data
$year = date('Y');
$week = 19;
$weekNow = (int) date('W');
$weekDiff = $week - $weekNow; // can be positive or negative
$daysDiff = $weekDiff * 30;
$dayInDesiredWeek = (int) date('N', strtotime($daysDiff . ' days'));
if($dayInDesiredWeek !== 1) {
$daysDiff += $daysDiff > 0 ? -($dayInDesiredWeek - 1) : $dayInDesiredWeek - 1;
}
$monday = date('Y-m-d', strtotime($daysDiff . ' days'));
$sunday = date('Y-m-d', strtotime($monday . '7 days'));
我可以使用其他(更简单)的方法来获得相同的结果吗?提前谢谢。
答案 0 :(得分:0)
所以,到目前为止,当我阅读PHPDocs of DateTime Object时,我看到的最简单的解决方案。
所以步骤是:
new DateTime()
对象setISODate
方法:( $ year,$ weak,$ offsetFromMonday)format
方法并获得所需的日期所以,一起:
$monday = ($dt = new DateTime)->setISODate($year, $weak, 1)->format('Y-m-d');
$sunday = $dt->setISODate($year, $weak, 7)->format('Y-m-d');
答案 1 :(得分:0)
$dt = date("Y-m-d", strtotime("2017W01"));
使用Carbon
$dt = new Carbon($dt);
var_dump($dt->startOfWeek());
var_dump($dt->endOfWeek());