【问题标题】:Loop through Calendar Weeks循环通过日历周
【发布时间】:2016-01-31 03:00:39
【问题描述】:

我在课堂上构建了这个函数:

class CalenderWeekHelper {
    public static function getCalenderWeek($year = 2016)
    {
        for ($i=1; $i <= 52; $i++)
        {
             $from = date("d.m.Y", strtotime("{$year}-W{$i}-1")); //Returns the date of monday in week
             $to   = date("d.m.Y", strtotime("{$year}-W{$i}-7")); //Returns the date of sunday in week
             $weekArray[$i] = array('start' => $from, 'end' => $to);

        }
        return $weekArray;
    }
}

然后这样称呼它:

$kw = CalenderWeekHelper::getCalenderWeek(2015);
echo $kw[1]['start']

但它仍然呼应我:

01.01.1970

我只想循环整个日历周,有人知道如何解决这个问题吗?

【问题讨论】:

  • 周数的长度应为 2 ---W01、W02 等。

标签: php arrays date for-loop strtotime


【解决方案1】:

有关 strtotime 的正确格式,请参阅以下答案: How to convert week number and year into unix timestamp?

返回的日期是星期一,所以可以加 6 天得到星期日:

$week = sprintf('%02s', $i); // make sure it is formatted in double figures
$from = date("d.m.Y", strtotime("{$year}W{$week}")); //Returns the date of monday in week
$to   = date("d.m.Y", strtotime("{$year}W{$week} +6 days")); //Returns the date of sunday in week

【讨论】:

  • 谢谢它到目前为止有效,一个问题是你的第一行做了什么excatly ($week = sprintf('%02s', $i);)?
  • 您应该查找php.net/sprintf 以了解该功能的具体细节。但是这种方式需要周数,如果它低于 10,则添加 0,因此它的长度始终为 2“04”。 % 表示变量,02 表示长度至少为 2 并用 0 填充,'s' 表示输出一个字符串。
猜你喜欢
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-16
  • 2019-05-12
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多