简体   繁体   English

获取当前一周的每一天

[英]Get every day of the current week

I need to get every day of the current week.我需要得到本周的每一天。

Here is what I have done so far, it seems to work but I want to know if I can do it better.这是我到目前为止所做的,它似乎有效,但我想知道我是否可以做得更好。

$weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
$days = [];
foreach($weekdays as $k => $v){
    $days[$k] = date('Y-m-d', strtotime(''.$v.' 0 week'));
}

For example using the \DateTime object and the modify method:例如使用\DateTime object 和修改方法:

<?php
$days = [];
$date = new \DateTime();
$date->modify('this week monday');
for ($i = 0; $i < 7; $i++) {
    $days[$i] = $date->format('Y-m-d');
    $date->modify('+1 day');
}

In the code we set the date object to the current week's monday and then cycle it 7 times by shifting the date to next day on each iteration.在代码中,我们将日期 object 设置为本周的星期一,然后通过在每次迭代中将日期移到下一天来循环它 7 次。

The complete list of supported formats for DateTime::modify is here . DateTime::modify 支持的格式的完整列表在这里

You don't need the array with the days of the week.您不需要包含星期几的数组。

$days = [];
for($i=0;$i<7;$i++){
    $days[$i] = date('Y-m-d', strtotime("Monday this week +$i days"));
}

The same with DateTime:与日期时间相同:

$days = [];
for($i=0;$i<7;$i++){
    $days[$i] = date_create("Monday this week +$i days")->format('Y-m-d');
}

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

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