根据周数和年份获取特定日期

时间:2022-09-26 18:49:35

I'm getting the year and the 'week-of-the-year' from the external source, which I'm not able to change. I'd like to get the date of Monday and Sunday of that concrete week. For now I've got the below code, but it seems pretty complicated.

我从外部来源获得了一年和“一周的一年”,我无法改变。我想得到那个具体周的周一和周日的日期。现在我已经得到了以下代码,但看起来相当复杂。

<?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'));

Is there any other (simpler) method I can use to get the same results? Thank you in advance.

有没有其他(更简单)的方法可以用来获得相同的结果?先感谢您。

2 个解决方案

#1


0  

 $dt = date("Y-m-d", strtotime("2017W01"));

use Carbon

 $dt = new Carbon($dt);

 var_dump($dt->startOfWeek());
 var_dump($dt->endOfWeek());  

#2


0  

So, the easiest solution I've seen so far, when I was reading the PHPDocs of DateTime Object.

所以,到目前为止,当我阅读DateTime Object的PHPDocs时,我看到的最简单的解决方案。

So the steps are:

所以步骤是:

  1. Create new DateTime() object
  2. 创建新的DateTime()对象

  3. Run it's setISODate method with params: ($year, $weak, $offsetFromMonday)
  4. 用params运行它的setISODate方法:($ year,$ weak,$ offsetFromMonday)

  5. then run format method and get the desired date
  6. 然后运行格式化方法并获得所需的日期

So, all together:

所以,一起:

$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"));

use Carbon

 $dt = new Carbon($dt);

 var_dump($dt->startOfWeek());
 var_dump($dt->endOfWeek());  

#2


0  

So, the easiest solution I've seen so far, when I was reading the PHPDocs of DateTime Object.

所以,到目前为止,当我阅读DateTime Object的PHPDocs时,我看到的最简单的解决方案。

So the steps are:

所以步骤是:

  1. Create new DateTime() object
  2. 创建新的DateTime()对象

  3. Run it's setISODate method with params: ($year, $weak, $offsetFromMonday)
  4. 用params运行它的setISODate方法:($ year,$ weak,$ offsetFromMonday)

  5. then run format method and get the desired date
  6. 然后运行格式化方法并获得所需的日期

So, all together:

所以,一起:

$monday = ($dt = new DateTime)->setISODate($year, $weak, 1)->format('Y-m-d');
$sunday = $dt->setISODate($year, $weak, 7)->format('Y-m-d');