简体   繁体   English

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

[英]Get specific day's date based on the week number and the year

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. 先感谢您。

So, the easiest solution I've seen so far, when I was reading the PHPDocs of DateTime Object . 因此,到目前为止,当我阅读DateTime ObjectPHPDocs时,这是我迄今为止见过的最简单的解决方案。

So the steps are: 因此,步骤如下:

  1. Create new DateTime() object 创建new DateTime()对象
  2. Run it's setISODate method with params: ($year, $weak, $offsetFromMonday) 使用参数运行它的setISODate方法:($ year,$ weak,$ offsetFromMonday)
  3. then run format method and get the desired date 然后运行format方法并获取所需的日期

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');
 $dt = date("Y-m-d", strtotime("2017W01"));

use Carbon 使用

 $dt = new Carbon($dt);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM