根据周数和年份获取特定日期
Get specific day's date based on the week number and the year
我从外部来源获取年份和 'week-of-the-year',我无法更改。我想获得那个具体周的星期一和星期日的日期。现在我有下面的代码,但它看起来很复杂。
<?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'));
我可以使用任何其他(更简单的)方法来获得相同的结果吗?提前谢谢你。
所以,这是我迄今为止看到的最简单的解决方案,当时我正在阅读 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');
$dt = date("Y-m-d", strtotime("2017W01"));
使用Carbon
$dt = new Carbon($dt);
var_dump($dt->startOfWeek());
var_dump($dt->endOfWeek());
我从外部来源获取年份和 'week-of-the-year',我无法更改。我想获得那个具体周的星期一和星期日的日期。现在我有下面的代码,但它看起来很复杂。
<?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'));
我可以使用任何其他(更简单的)方法来获得相同的结果吗?提前谢谢你。
所以,这是我迄今为止看到的最简单的解决方案,当时我正在阅读 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');
$dt = date("Y-m-d", strtotime("2017W01"));
使用Carbon
$dt = new Carbon($dt);
var_dump($dt->startOfWeek());
var_dump($dt->endOfWeek());