Receive all workdays per week for a specific date

So, I have one date as a string:

2011/06/01

I need to get 5 DateTime objects from it that correspond to five weekdays (Monday through Friday) this week, for example. for the date above I need 2011-05-30 to 2011-06-03.

How to do it? I know that I can:

$dateTime = new DateTime('2011/06/01');

But I’m kind of stuck there :) I know, I'm embarrassed.

+3
source share
4 answers

You can use DatePeriod :

$firstMondayThisWeek= new DateTime('2011/06/01');
$firstMondayThisWeek->modify('tomorrow');
$firstMondayThisWeek->modify('last Monday');

$nextFiveWeekDays = new DatePeriod(
    $firstMondayThisWeek,
    DateInterval::createFromDateString('+1 weekdays'),
    4
);

print_r(iterator_to_array($nextFiveWeekDays));

Note that it DatePeriodis Iterator, therefore, if you are not really fixed in the dates in the array, you can just go with the container DatePeriod.

The above will give something like ( demo )

 Array
(
[0] => DateTime Object
    (
        [date] => 2011-05-30 00:00:00
        [timezone_type] => 3
        [timezone] => Europe/Berlin
    )

[1] => DateTime Object
    (
        [date] => 2011-05-31 00:00:00
        [timezone_type] => 3
        [timezone] => Europe/Berlin
    )

[2] => DateTime Object
    (
        [date] => 2011-06-01 00:00:00
        [timezone_type] => 3
        [timezone] => Europe/Berlin
    )

[3] => DateTime Object
    (
        [date] => 2011-06-02 00:00:00
        [timezone_type] => 3
        [timezone] => Europe/Berlin
    )

[4] => DateTime Object
    (
        [date] => 2011-06-03 00:00:00
        [timezone_type] => 3
        [timezone] => Europe/Berlin
    )
)

5.3

$firstMondayInWeek = strtotime('last Monday', strtotime('2011/06/01 +1 day'));
$nextFiveWeekDays = array();
for ($days = 1; $days <= 5; $days++) {
    $nextFiveWeekDays[] = new DateTime(
        date('Y-m-d', strtotime("+$days weekdays", $firstMondayInWeek))
    );
}

, DateTime , API . , , DateTime .

+7

Try:

$dayAfter = $dateTime->modify('+1 day');

. php .

+1

('w') 0 ( ) 6 ( ). strtotime ( "+ 1 ", [ ]) . , .

+1
source

It works:

$d = date('N', strtotime('2011/06/01'));
// here N means ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)
$week = array();
for($i = 1; $i < $d; ++$i){
    $dateTime = new DateTime('2011/06/01');
    for($j = 0; $j < $i; ++$j){
        $dateTime->modify('-1 day');
    }   
    $week[] = $dateTime;
}
$week[] = new DateTime('2011/06/01');
for($i = $d+1; $i <= 7; ++$i){
    $dateTime = new DateTime('2011/06/01');
    for($j = 0; $j < $i - $d; ++$j){
        $dateTime->modify('+1 day');
    }   
    $week[] = $dateTime;
}
sort($week);

foreach($week as $day){
    echo $day->format('Y-m-d H:i:s'), '<br />';
}
0
source

All Articles